#!/usr/bin/env python3 """ verify_identities.py -- programme 0011, TASK 1: the exact identities, two independent routes. Route (a): direct pair enumeration. Route (b): the pair-free formulas of sievecore. c = #{pN} 1/(pq). (I1) S = (H^2 - H2)/2 - T (I2) Phi = (N/2)(H^2 - H2) - N T (I3) A = N S - F (I4) c = #{pq<=N}, F = N S - A <- the two definitions (I5) F = N S - A <- the crux (used for all measurement) (I6) A = (N/2)(H^2 - H2) - N T - F Run: .venv/bin/python3 verify_identities.py """ from __future__ import annotations import sys from math import isqrt import numpy as np sys.path.insert(0, "src") from sievecore import primes_upto, floor_sum, semiprime_count, H_H2, tail_T # noqa: E402 def brute(N: int) -> dict: allpr = primes_upto(N // 2).tolist() S = 0.0 c = 0 A = 0 F = 0.0 T = 0.0 for i, p in enumerate(allpr): for q in allpr[i + 1:]: v = p * q if v <= N: S += 1.0 / v c += 1 A += N // v F += (N % v) / v else: T += 1.0 / v pr = np.array(allpr, dtype=np.int64) inv = 1.0 / pr.astype(np.float64) H = float(inv.sum()) H2 = float((inv * inv).sum()) return dict(N=N, S=S, c=c, A=A, F=F, H=H, H2=H2, T=T) def formulas(N: int) -> dict: pr = primes_upto(N // 2) inv = 1.0 / pr.astype(np.float64) pref = np.concatenate(([0.0], np.cumsum(inv))) small = pr[pr <= isqrt(N)] ic = np.searchsorted(pr, N // small, side="right") ip = np.searchsorted(pr, small, side="right") S = float(np.sum((1.0 / small) * (pref[ic] - pref[ip]))) c = int((ic - ip).sum()) A = floor_sum(pr, N) H, H2 = H_H2(pr, N) T = tail_T(pr, N) Phi = float(N) * S return dict(N=N, S=S, c=c, A=A, H=H, H2=H2, T=T, Phi=Phi) def main() -> None: print("== TASK 1: exact identities (direct pairs vs formulas) ==") print(f"{'N':>9} {'c':>8} {'rel route diff':>15} {'|I1|':>7} {'|I2|':>7} {'|I3|':>7} " f"{'|I4|':>7} {'|I5|':>7} {'|I6|':>7}") for N in [1000, 10000, 100000, 1000000, 10000000]: f = formulas(N) b = brute(N) if N <= 100000 else None n2 = f["H"] ** 2 - f["H2"] if b: rd = max(abs(f[k] - b[k]) / max(1.0, abs(b[k])) for k in ("S", "A", "H", "H2", "T")) else: rd = float("nan") I1 = f["S"] - (n2 / 2 - f["T"]) I2 = f["Phi"] - ((N * n2) / 2 - N * f["T"]) F = f["Phi"] - f["A"] I3 = f["A"] - (N * f["S"] - F) I4 = F - (f["Phi"] - f["A"]) I5 = F - (N * f["S"] - f["A"]) I6 = f["A"] - ((N * n2) / 2 - N * f["T"] - F) print(f"{N:>9} {f['c']:>8} {rd:>15.2e} {I1:>7.1e} {I2:>7.1e} {I3:>7.1e} " f"{I4:>7.1e} {I5:>7.1e} {I6:>7.1e}") print() print("== TASK 2: (K') and the exact finite-N defect ==") print(f"{'N':>11} {'c':>11} {'Phi':>16} {'A':>16} {'F=Phi-A':>12} {'F/N':>9} {'F/(Nm/L)':>9}") for N in [10 ** 5, 10 ** 6, 10 ** 7, 10 ** 8]: f = formulas(N) F = f["Phi"] - f["A"] L = np.log(N) m = np.log(L) print(f"{N:>11} {f['c']:>11} {f['Phi']:>16.1f} {f['A']:>16} {F:>12.1f} " f"{F/N:>9.5f} {F/(N*m/L):>9.5f}") if __name__ == "__main__": main()