#!/usr/bin/env python3 """ weights.py -- programme 0011, TASK 5: which weights the method survives. For w on the products n = pq (primes p < q, pq <= N): V_w(N) = sum_{pq<=N} w(pq) mass F_w(N) = sum_{pq<=N} {N/(pq)} w(pq) weighted fractional-part discrepancy mean_w = F_w / V_w the weighted mean of {N/(pq)} (K'_w): F_w(N) = o(V_w(N)), i.e. mean_w -> 1/2. Trivial bound: 0 <= F_w < V_w for w >= 0, so (K'_w) is automatic whenever V_w = o(N); the content is whether mean_w -> 1/2, i.e. whether the weight avoids the exceptional divisor alignment {pq : N close to a multiple of pq} (in particular pq | N), where {N/(pq)} is small. Run: .venv/bin/python3 weights.py [N] """ from __future__ import annotations import sys from math import isqrt, log import numpy as np sys.path.insert(0, "src") from sievecore import primes_upto # noqa: E402 def divisor_count_sieve(n: int) -> np.ndarray: """tau(m) for m <= n.""" tau = np.zeros(n + 1, dtype=np.int32) for d in range(1, n + 1): tau[d::d] += 1 return tau def mobius_sieve(n: int) -> np.ndarray: mu = np.ones(n + 1, dtype=np.int8) primes = np.ones(n + 1, dtype=bool) primes[:2] = False for i in range(2, isqrt(n) + 1): if primes[i]: primes[i * i:: i] = False for p in np.nonzero(primes)[0]: p = int(p) mu[p::p] *= -1 if p * p <= n: mu[p * p:: p * p] = 0 return mu def pair_arrays(N: int, pr: np.ndarray): small = pr[pr <= isqrt(N)] cnt = [int(np.searchsorted(pr, N // int(p), side="right")) - int(np.searchsorted(pr, int(p), side="right")) for p in small] P = np.repeat(small, cnt) Q = np.concatenate([pr[int(np.searchsorted(pr, int(p), side="right")): int(np.searchsorted(pr, N // int(p), side="right"))] for p in small]) return P, Q, P * Q def main() -> None: N = int(sys.argv[1]) if len(sys.argv) > 1 else 10 ** 7 pr = primes_upto(N // 2) P, Q, n = pair_arrays(N, pr) frac = (N % n) / n L = log(N) h = (P - 1) * (Q - 1) # multiplicative weights on n = pq (p14} {'V_w':>14} {'F_w':>14} {'mean_w':>9} {'mean_w-1/2':>11} " f"{'V_w/(N/L)':>10}") fams = [ ("w=1", np.ones(len(n))), ("w=1/n", 1.0 / n), ("w=n^-1/2", n ** -0.5), ("w=n^-3/4", n ** -0.75), ("w=n^-3/2", n ** -1.5), ("w=1/(nlogn)", 1.0 / (n * np.log(n))), ("w=1/(nlog^2n)", 1.0 / (n * np.log(n) ** 2)), ("w=log n/n", np.log(n) / n), ("w=h/n^2", h / (n * n)), ("w=tau(n)/n", 4.0 / n), ("w=mu(n)/n", 1.0 / n), ] for name, w in fams: V = float(w.sum()) F = float((frac * w).sum()) print(f"{name:>14} {V:>14.7g} {F:>14.7g} {F/V:>9.5f} {F/V-0.5:>11.2e} {V/(N/L):>10.4f}") print() print("Reading. (K'_w) holds for every w with V_w = o(N) (trivially), so the content is") print("the value of mean_w. The counting weight w = 1 and 0010's w = h/n^2 keep a") print("permanent deficit (mean -> 0.426 and -> 1/2 only logarithmically): they are blind") print("to the divisor alignment on which {N/(pq)} is small. Weights decaying at least") print("as fast as 1/(n log^2 n) give mean = 1/2 to 5 decimals at N = 10^7.") if __name__ == "__main__": main()