"""Minimal exact-F sieve. Built from the definition, no algebraic shortcuts. head(h) = prod_{3<=p<=h+2} f_p(h) T(h) = prod_{8= p-2. So (p, r) is one arithmetic progression. Everything accumulates in log space; a factor that is exactly 0 sets a separate boolean mask. """ from __future__ import annotations import math import sys import numpy as np sys.path.insert(0, "work/route176") from fobj import HEAD6, F_engine, primes_upto # noqa: E402 def _primes(n: int) -> list[int]: return primes_upto(n) def F_array(H: int) -> np.ndarray: pr = _primes(H + 2) # log head: difference array; log T: point increments then prefix sum L = np.zeros(H + 3, dtype=np.float64) dt = np.zeros(H + 4, dtype=np.float64) zero = np.zeros(H + 3, dtype=bool) for p in pr: if p < 3: continue start = p - 2 if start > H: break # per-residue values, straight from nu_p; each (p, r) is one arithmetic progression for r in range(p): nu = len({0, 2, r, (r + 2) % p}) f = (p - nu) / p / ((p - 2) / p) ** 2 k = start + ((r - start) % p) if k > H: continue if f == 0.0: zero[k : H + 1 : p] = True continue L[k : H + 1 : p] += math.log(f) # window tail if p > 8: dt[p - 2] += math.log((p - 1) / (p - 2)) lp = L lt = np.cumsum(dt)[: H + 3] F = (5.0 / 3.0) / float(HEAD6) * np.exp(lp) * np.exp(lt) F[zero] = 0.0 h = np.arange(H + 3) F[(h % 3 != 0) | (h < 6)] = 0.0 return F def validate(limit: int = 3998) -> tuple[int, float]: F = F_array(limit) worst, n = 0.0, 0 for h in range(6, limit + 1, 3): e = float(F_engine(h)) if e <= 0: if F[h] != 0.0: worst = max(worst, 1.0) continue worst = max(worst, abs(e - F[h]) / e) n += 1 return n, worst if __name__ == "__main__": n, worst = validate(3998) print(f"validate: {n} supported h <= 3998, max rel dev {worst:.3e}")