""" sievecore.py -- exact instruments for programme 0011. Primes p < q, N = x. All "short" sums are over primes <= N/2 (the largest prime that can appear in a pair pq <= N with p < q is q = N/2). c(N) = #{pq <= N} semiprime (2-almost-prime) count S(N) = sum_{pq<=N} 1/(pq) semiprime reciprocal sum A(N) = sum_{pq<=N} floor(N/(pq)) lattice-point (floor) sum F(N) = sum_{pq<=N} {N/(pq)} fractional-part discrepancy Phi(N) = N S(N) the area under the hyperbola H = sum_{p<=N/2} 1/p, H2 = sum_{p<=N/2} 1/p^2 T = sum_{pN} 1/(pq) hyperbolic tail EXACT IDENTITIES (proved in PROGRAMME.md, verified by verify_identities.py): (I1) S = (H^2 - H2)/2 - T (Gaussian/product formula) (I2) Phi = (N/2)(H^2 - H2) - N T (I3) A = N S - F (floor + frac = value, termwise) (I4) c = A + F (termwise, the definition of F) (I5) c = N S - F (hence c = N S - F) (I6) F = (Phi - c)/(N - 1) (the crux) (I6) is the crux: F = (Phi(N) - c(N))/(N - 1), both sides O(pi(N)) to compute. """ from __future__ import annotations from math import isqrt import numpy as np def primes_upto(n: int) -> np.ndarray: """All primes <= n as int64.""" if n < 2: return np.zeros(0, dtype=np.int64) s = np.ones(n + 1, dtype=bool) s[:2] = False for i in range(2, isqrt(n) + 1): if s[i]: s[i * i:: i] = False return np.nonzero(s)[0].astype(np.int64) def semiprime_count(pr: np.ndarray, N: int) -> int: """c(N) = #{p int: """A(N) = sum_{p tuple[float, float]: """H = sum 1/p, H2 = sum 1/p^2 over primes <= N/2.""" inv = 1.0 / pr.astype(np.float64) return float(inv.sum()), float((inv * inv).sum()) def tail_T(pr: np.ndarray, N: int) -> float: """T(N) = sum_{pN} 1/(pq) = sum_q (1/q)[P(N/2) - P(max(q, N/q))].""" inv = 1.0 / pr.astype(np.float64) pref = np.concatenate(([0.0], np.cumsum(inv))) P = float(pref[-1]) lo = np.maximum(pr, N // pr) idx = np.searchsorted(pr, lo, side="right") return float(np.sum(inv * (P - pref[idx]))) def all_quantities(N: int, pr: np.ndarray | None = None) -> dict: """Every exact quantity at N.""" if pr is None: pr = primes_upto(N // 2) H, H2 = H_H2(pr, N) T = tail_T(pr, N) S = (H * H - H2) / 2.0 - T Phi = float(N) * S c = semiprime_count(pr, N) F = (Phi - c) / (N - 1) A = c - F return dict(N=N, pr=pr, H=H, H2=H2, T=T, S=S, A=A, c=c, Phi=Phi, F=F)