TExcelTAD
Home › Number Theory & Cryptography › The Sieve of Eratosthenes

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 NN in about Nlog⁡log⁡NN \log \log N steps: tens of millions per second even in NumPy.

The algorithm

Write down 2,3,…,N2, 3, \ldots, N. 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 p2p^2: smaller multiples kpkp with k<pk < p were already removed by the prime factors of kk.
  • Stop once p2>Np^2 > N: every composite ≤N\le N has a prime factor ≤N\le \sqrt{N}.
python · try it yourself
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 10710^7 entries takes 10 MB:

python · try it yourself
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 Nlog⁡log⁡NN \log \log N?

The work is ∑p≤NN/p\sum_{p \le \sqrt{N}} N/p, and the sum of reciprocals of primes up to xx grows like ln⁡ln⁡x\ln \ln x (Mertens' theorem). So the sieve is nearly linear in NN.

The smallest-prime-factor sieve

A small change records, for each nn, its smallest prime factor. Then any n≤Nn \le N factors in O(log⁡n)O(\log n) divisions, useful when you need many factorizations:

python · try it yourself
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 [L,L+W)[L, L + W) far from 0, sieve the window with the primes up to L+W\sqrt{L + W} only. Memory is WW instead of L+WL + W; this is how prime tables up to 101810^{18} and beyond are produced.

python · try it yourself
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.primerange and sympy.sieve keep 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 72=49>307^2 = 49 > 30); 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 72=49>307^2 = 49 > 30, everything left is prime: ten primes.

Exercise 2: Twin primes (code)

Count twin prime pairs (p,p+2)(p, p + 2) below one million.

Answer
Solution
python · try it yourself
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 p2p^2?

When sieving with p=7p = 7, why is it safe to skip 14,21,28,35,4214, 21, 28, 35, 42?

Answer

Each has a prime factor smaller than 7 and was crossed out already.

Solution

7k7k with k<7k < 7 has kk's prime factors, all smaller than 7: 14=2⋅714 = 2 \cdot 7, 21=3⋅721 = 3 \cdot 7, 28=22⋅728 = 2^2 \cdot 7, 35=5⋅735 = 5 \cdot 7, 42=2⋅3⋅742 = 2 \cdot 3 \cdot 7. They were removed in earlier passes. The first multiple that only 7 can remove is 49=7249 = 7^2.

Test yourself

When sieving up to NN, you can stop at the prime pp once…

  1. p>N/2p > N/2
  2. p2>Np^2 > N
  3. p>log⁡Np > \log N
  4. p=Np = N

The running time of the sieve of Eratosthenes up to NN is about…

  1. N2N^2
  2. Nlog⁡log⁡NN \log \log N
  3. N\sqrt{N}
  4. 2N2^N

A smallest-prime-factor table lets you factor any n≤Nn \le N in about…

  1. n\sqrt{n} steps
  2. log⁡n\log n steps
  3. one step
  4. nn steps