omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / square-free-integers / oracle.py
| 1 | # Independent reference for "Square-free integers" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | import math |
| 4 | def squarefree(n): |
| 5 | m, p = n, 2 |
| 6 | while p * p <= m: |
| 7 | if m % p == 0: |
| 8 | m //= p |
| 9 | if m % p == 0: |
| 10 | return False |
| 11 | p += 1 |
| 12 | return True |
| 13 | print("square-free integers from 1 to 145: " + " ".join(str(n) for n in range(1, 146) if squarefree(n))) |
| 14 | B = 10 ** 12 |
| 15 | print(f"square-free integers from {B} to {B + 145}: " + " ".join(str(n) for n in range(B, B + 146) if squarefree(n))) |
| 16 | # counts by the Moebius formula: Q(x) = sum mu(d) * floor(x / d^2) |
| 17 | N = 1000 |
| 18 | mu = [1] * (N + 1) |
| 19 | isp = [True] * (N + 1) |
| 20 | for p in range(2, N + 1): |
| 21 | if isp[p]: |
| 22 | for j in range(p, N + 1, p): |
| 23 | if j > p: |
| 24 | isp[j] = False |
| 25 | mu[j] = -mu[j] |
| 26 | for j in range(p * p, N + 1, p * p): |
| 27 | mu[j] = 0 |
| 28 | for e in range(2, 7): |
| 29 | x = 10 ** e |
| 30 | print(f"square-free integers up to {x}: {sum(mu[d] * (x // (d * d)) for d in range(1, math.isqrt(x) + 1))}") |