The Sieve of Eratosthenes
Testing numbers one by one is wasteful when you want all primes up to a bound. The sieve of Eratosthenes crosses out multiples instead of dividing, and finds every prime below in about steps: tens of millions per second even in NumPy.
The algorithm
Write down . The first number not crossed out, 2, is prime; cross out its multiples. The next survivor, 3, is prime; cross out its multiples. Continue. Two refinements:
- Start crossing out at : smaller multiples with were already removed by the prime factors of .
- Stop once : every composite has a prime factor .
def sieve(N):
is_p = [True] * (N + 1)
is_p[0] = is_p[1] = False
p = 2
while p * p <= N:
if is_p[p]:
for m in range(p * p, N + 1, p):
is_p[m] = False
p += 1
return [n for n in range(N + 1) if is_p[n]]
ps = sieve(100)
print(len(ps), ps)25 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
A vectorized sieve
The inner loop is a strided write, which NumPy does in one slice assignment. A boolean array of entries takes 10 MB:
import numpy as np
def np_sieve(N):
is_p = np.ones(N + 1, dtype=bool)
is_p[:2] = False
for p in range(2, int(N**0.5) + 1):
if is_p[p]:
is_p[p * p :: p] = False
return np.flatnonzero(is_p)
ps = np_sieve(10**7)
print(len(ps), ps[-3:].tolist())664579 [9999971, 9999973, 9999991]
There are 664579 primes below ten million.
Why ?
The work is , and the sum of reciprocals of primes up to grows like (Mertens' theorem). So the sieve is nearly linear in .
The smallest-prime-factor sieve
A small change records, for each , its smallest prime factor. Then any factors in divisions, useful when you need many factorizations:
def spf_sieve(N):
spf = list(range(N + 1))
for p in range(2, int(N**0.5) + 1):
if spf[p] == p:
for m in range(p * p, N + 1, p):
if spf[m] == m:
spf[m] = p
return spf
spf = spf_sieve(10000)
def factor(n):
out = []
while n > 1:
out.append(spf[n]); n //= spf[n]
return out
print(factor(9240), factor(9973), factor(8192))[2, 2, 2, 3, 5, 7, 11] [9973] [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
Segmented sieves
To list primes in a window far from 0, sieve the window with the primes up to only. Memory is instead of ; this is how prime tables up to and beyond are produced.
from math import isqrt
def primes_in(L, W):
small = [p for p in range(2, isqrt(L + W) + 1) if all(p % q for q in range(2, isqrt(p) + 1))]
mark = [True] * W
for p in small:
start = max(p * p, (L + p - 1) // p * p)
for m in range(start, L + W, p):
mark[m - L] = False
return [L + i for i in range(W) if mark[i] and L + i > 1]
print(primes_in(10**9, 100))[1000000007, 1000000009, 1000000021, 1000000033, 1000000087, 1000000093, 1000000097]
In software
- Sieves generate the small-prime tables that RSA key generation uses to throw away most candidates before the expensive Miller-Rabin test.
sympy.primerangeandsympy.sievekeep an extendable sieve internally.
Exercises
Exercise 1: By hand
Sieve the numbers 2 to 30. Which primes do you cross out multiples of, and which primes remain?
Answer
Cross out multiples of 2, 3, 5 (since ); remaining: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.
Solution
Multiples of 2 from 4, of 3 from 9, of 5 from 25 are removed. Since , everything left is prime: ten primes.
Exercise 2: Twin primes (code)
Count twin prime pairs below one million.
Answer
Solution
import numpy as np
N = 10**6
is_p = np.ones(N + 1, dtype=bool); is_p[:2] = False
for p in range(2, int(N**0.5) + 1):
if is_p[p]:
is_p[p * p :: p] = False
print(int(np.count_nonzero(is_p[:-2] & is_p[2:])))8169
Whether there are infinitely many twin primes is still an open problem.
Exercise 3: Why start at ?
When sieving with , why is it safe to skip ?
Answer
Each has a prime factor smaller than 7 and was crossed out already.
Solution
with has 's prime factors, all smaller than 7: , , , , . They were removed in earlier passes. The first multiple that only 7 can remove is .
Test yourself
When sieving up to , you can stop at the prime once…
The running time of the sieve of Eratosthenes up to is about…
A smallest-prime-factor table lets you factor any in about…
- steps
- steps
- one step
- steps