#!/usr/bin/env python3 """ quantities.py -- programme 0011, TASK 2/4: the (K') measurement, pair-free. Objects at N (primes p 0 is (K') F/(N m/L) -> C_F, the Selberg-Delange coefficient (m = loglog N, L = log N) F/c the "excess over independence" normalisation used in 0009/0010 (c - N S)/(N) the exact finite-N defect Run: .venv/bin/python3 quantities.py [N ...] """ from __future__ import annotations import sys import time from math import isqrt, log import numpy as np sys.path.insert(0, "src") from sievecore import primes_upto, floor_sum, semiprime_count # noqa: E402 def evaluate(N: int, pr: np.ndarray) -> dict: half = N // 2 inv = 1.0 / pr.astype(np.float64) pref = np.concatenate(([0.0], np.cumsum(inv))) # pref[i] = sum_{p <= pr[i-1]} 1/p r = isqrt(N) small = pr[pr <= r] cuts = N // small ic = np.searchsorted(pr, cuts, 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) F = float(N) * S - float(A) L = log(N) m = log(L) return dict(N=N, S=S, Phi=N * S, c=c, A=A, F=F, L=L, m=m) def main() -> None: Ns = [int(a) for a in sys.argv[1:]] or [10 ** 4, 10 ** 5, 10 ** 6, 10 ** 7, 10 ** 8] pr = primes_upto(max(Ns) // 2) print("== (K') = F(N) = o(N), and its sharp constants ==") print(f"{'N':>11} {'S':>11} {'c':>11} {'A':>15} {'F':>13} {'F/N':>9} {'F/c':>8} " f"{'F/(N m/L)':>10} {'F*L/(N m)':>10}") rows = [] for N in Ns: t0 = time.time() d = evaluate(N, pr) rows.append(d) print(f"{d['N']:>11} {d['S']:>11.6f} {d['c']:>11} {d['A']:>15} {d['F']:>13.1f} " f"{d['F']/N:>9.5f} {d['F']/d['c']:>8.4f} {d['F']/(N*d['m']/d['L']):>10.5f} " f"{d['F']*d['L']/(N*d['m']):>10.5f} [{time.time()-t0:.1f}s]") print() print("== exact 'area minus count' defect and the two marginals ==") print(f"{'N':>11} {'Phi':>16} {'c':>11} {'Phi-c':>16} {'(Phi-c)/N':>11} {'Phi/c':>10}") for d in rows: print(f"{d['N']:>11} {d['Phi']:>16.1f} {d['c']:>11} {d['Phi']-d['c']:>16.1f} " f"{(d['Phi']-d['c'])/d['N']:>11.5f} {d['Phi']/d['c']:>10.3f}") print() print("== stability of the Selberg-Delange coefficient C_F = lim F L/(N loglogN) ==") print(" (the coefficient of N loglogN/logN in the fractional-part sum)") for d in rows: print(f" N = {d['N']:>11}: C_F = {d['F']*d['L']/(d['N']*d['m']):.6f}") if __name__ == "__main__": main()