Mental model
A number greater than 1 is prime if no smaller number other than 1 divides it. Testing one number k by trial division up to √k is fine; testing every number up to n that way repeats a lot of work.
The sieve turns the question around: instead of asking "does anything divide k?", every prime announces its multiples. Write down 2 … n. The smallest number not yet crossed out is prime; cross out all its multiples; repeat. Whatever survives has no smaller prime factor, so it is prime.
The algorithm
composite = array of n + 1 false values
for p = 2, 3, … while p * p <= n:
if composite[p]: continue # not prime: a smaller prime already did its work
for m = p * p, p * p + p, … while m <= n:
composite[m] = true
return every k in 2 … n with composite[k] == false
The lab lays 1 … n out in rows of ten. The current prime p has a pin, the number being crossed out
is labelled with its factorisation k·p, crossed-out numbers fade, and primes light up.
Why start at p²?
Every multiple k · p with k < p has a prime factor smaller than p (a factor of k), so it was crossed out when that smaller prime was processed. The first multiple that may still be unmarked is p · p. For p = 7 and n = 50: 14, 21, 28, 35 and 42 are already gone; only 49 is new.
Why stop when p² > n?
A composite number c ≤ n can be written as c = a · b with 2 ≤ a ≤ b, so a² ≤ c ≤ n: it has a factor at most √n, and therefore a prime factor at most √n. Once p² > n, every composite up to n has been crossed out by some prime below p. For n = 50 only 2, 3, 5 and 7 do any marking (preset n = 50); 11² = 121 is too large.
Complexity
Prime p crosses out about n / p numbers. Summed over the primes up to √n:
n/2 + n/3 + n/5 + n/7 + … = n · Σ 1/p ≈ n · ln ln n
The sum of reciprocals of primes up to x grows like ln ln x (Mertens' second theorem), which is why the sieve is O(n log log n) time, practically linear: ln ln 10⁹ ≈ 3. Memory is O(n) flags.
Some numbers are crossed out more than once, 12 by 2 and by 3, 30 by 2, 3 and 5. The lab's Repeat marks metric counts them. A linear sieve avoids repeats by crossing out each composite only by its smallest prime factor, reaching O(n), at the price of storing the prime list as it goes.
| Method | Time to list primes ≤ n | Memory |
|---|---|---|
| Trial division of each k up to √k | O(n √n) (less with only prime divisors) | O(1) besides the output |
| Sieve of Eratosthenes | O(n log log n) | O(n) flags |
| Linear sieve | O(n) | O(n) flags + primes |
| Segmented sieve | O(n log log n) | O(√n) at a time |
For a single primality test of a large number, use trial division up to √k or Miller–Rabin. For many queries up to a known bound, sieve once and look up.
Practical details
Overflow in the loop bounds. p * p <= n overflows a 32-bit int when p exceeds 46,340, even if
n itself fits. The C#, Java and C++ listings write p <= n / p instead. The inner m += p can also
overflow when n is within p of int.MaxValue; for such n use 64-bit loop variables.
Memory. A bool[] in C# and Java uses one byte per flag, and a Python list of booleans one
pointer (8 bytes) per entry. For large n:
- C#:
BitArray, or aulong[]with your own masks (the bit lesson'ssetandtest); - Java:
java.util.BitSet; - Python:
bytearray(n + 1), which also allows slice assignmentcomposite[p*p::p] = b"\x01" * len(range(p*p, n + 1, p))to cross out a whole progression at C speed; - C++:
std::vector<bool>already packs one flag per bit (the listing uses it), at the cost of proxy references instead of realbool&.
Only odd numbers need storing after 2, which halves memory again. Beyond memory limits, a segmented sieve processes [L, L + Δ) blocks using the primes up to √n.
Cache behaviour. Each prime walks the whole array with stride p, which misses the cache for large n; segmented sieves fix this too, because each block fits in cache.
Language notes
- C#:
new bool[n + 1]is zero-initialised (all false).checkedarithmetic catches the bound overflow if you prefer an exception to a rewrite. - Java:
boolean[]is also zero-initialised;BitSet.nextClearBit(k)walks to the next candidate. - Python: the listing's outer loop checks
p * p > nexplicitly (ints never overflow);math.isqrt(n)gives the exact integer square root for the bound, unlikeint(n ** 0.5), which can be off by one for large n because of floating point. - C++:
std::vector<bool>(n + 1)is false-initialised; index it withstd::size_t, and avoidstd::sqrtfor the bound for the same floating-point reason.
The teaching implementation
The sieve shares a source file with Euclid's algorithm in each language. Each language reads one shared fixture (n = 0, 1, 2, 3, 4, perfect squares such as 25 and 49, a prime limit 97, 150) and compares the result with trial division for every n below 200 and for n = 5,000, where there are 669 primes. The unit tests of the trace also check that every crossed-out number is first marked by its smallest prime factor and that each prime starts at p².
Common mistakes
- Starting at 2p instead of p²: correct, but does redundant work.
- Looping p up to n instead of √n: correct, but the outer loop runs n times for nothing.
- Forgetting that 0 and 1 are not prime when collecting the result.
- Writing
p * p <= nin 32-bit arithmetic for large n. - Using
sqrtin floating point for the bound without checking the result.
Edge cases
- n < 2: no primes; the outer loop never runs.
- n = 2 or 3: the outer loop does not run either (2² > 3), and the collection step returns them.
- n a perfect square (25, 49): p = √n still runs, because p² ≤ n, and crosses out n itself.
Worked practice
1. Which numbers does p = 5 cross out for n = 40, and which of them were already crossed out?
Answer
25, 30, 35 and 40. 30 (by 2 and 3) and 40 (by 2) were already crossed out; 25 and 35 are new.
2. For n = 1,000, which primes do any crossing out?
Answer
The primes up to √1000 ≈ 31.6: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31.
3. How would you find all primes in [10⁹, 10⁹ + 10⁶] without an array of size 10⁹?
Answer
Sieve the primes up to √(10⁹ + 10⁶) ≈ 31,639 first. Then allocate flags for the million numbers in the range only, and for each small prime p cross out its multiples from the first one ≥ max(p², 10⁹) inside the range. That is a segmented sieve.
Summary
- Each prime crosses out its multiples; what survives is prime.
- Start at p² (smaller multiples have smaller prime factors) and stop when p² > n (every composite has a prime factor ≤ √n).
- O(n log log n) time, O(n) memory; pack flags as bits and write the bound as
p <= n / p.