Q&A-8Teach the sieve of Eratosthenes to an engineer who has only seen it as a rule of thumb.
Answer
The 90-second answer
The sieve answers "which numbers up to n are prime" in one pass, without ever testing a number for primality. Keep a boolean array is_prime[0..n], all true. Walk p from 2 upward; when is_prime[p] is still true, p is prime, so mark every multiple of p from p² onward as composite. Stop when p² > n. Everything still true is prime.
Two things make it work. First, the invariant: when you reach p, every composite ≤ p² has already been marked by a smaller prime factor, so an unmarked p is genuinely prime. Second, starting at p² rather than 2p: the multiples 2p, 3p, …, (p−1)p were already marked by 2, 3, …, p−1. That is not an optimisation you can skip: it is what makes the total work O(n log log n) instead of O(n log n).
Bound semantics matter: this returns primes ≤ n inclusive, array length n+1. "Primes below n" is a different contract.
Code
def sieve(n):
"""is_prime[i] == 1 iff i is prime, for 0 <= i <= n."""
is_prime = bytearray([1]) * (n + 1)
if n >= 0: is_prime[0] = 0
if n >= 1: is_prime[1] = 0
p = 2
while p * p <= n:
if is_prime[p]:
is_prime[p*p::p] = bytearray(len(range(p*p, n + 1, p)))
p += 1
return is_primeTrace, n = 30
- p=2: prime. Mark 4, 6, …, 30.
- p=3: prime. Mark 9, 12, …, 30.
- p=4:
is_prime[4] == 0, skip. - p=5: prime. Mark 25, 30.
- p=6: 36 > 30, stop.
Survivors: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.
Why log log n
Total marking writes = Σ n/p over primes p ≤ √n. For n = 10⁶ that is ≈ 2.9×10⁶ writes (n·ln ln n ≈ 2.63×10⁶ plus the constant term). Trial division of all 10⁶ values by the 168 primes ≤ 1000 is up to 1.7×10⁸ modulo operations. Same answer, roughly 60× fewer operations, and each is a store rather than a division.
Failure modes
- Memory: the bytearray is 1 byte per number. 1 GB at n = 10⁹. Bit-packed it is 125 MB. The slice assignment also allocates a temporary: at n = 10⁹, marking p=2 allocates a 500 MB temp. Chunk the marking or use a segmented sieve.
- n = 0 or 1: the guards exist because
is_prime[0]would otherwise be 1. - Sparse queries: if you need primality for 20 numbers near 10¹², sieving to 10¹² is absurd. Miller–Rabin, or trial division by primes ≤ 10⁶, wins.
When not to use it
Sieve when queries are dense within a known bound. Test individually when they are sparse or the values sit far above any bound you would want to allocate.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.