omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / hamming-numbers / oracle.py
| 1 | # Independent reference for "Hamming numbers" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | # Cross-check, WolframLanguageEvaluator: s = Sort[Flatten[Table[2^i 3^j 5^k, {i,0,40},{j,0,30},{k,0,20}]]]; |
| 4 | # {Take[s, 20], s[[1691]]} -> {{1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36}, 2125764000} |
| 5 | import heapq |
| 6 | # a min-heap: pop the smallest, push its multiples, skip repeats |
| 7 | h, seen, out = [1], {1}, [] |
| 8 | while len(out) < 1691: |
| 9 | v = heapq.heappop(h) |
| 10 | out.append(v) |
| 11 | for f in (2, 3, 5): |
| 12 | if v * f not in seen: |
| 13 | seen.add(v * f) |
| 14 | heapq.heappush(h, v * f) |
| 15 | print("first 20:", *out[:20]) |
| 16 | print("1691st:", out[1690]) |