Sieve of Eratosthenes

6 min read#number-theory

An ancient algorithm that finds every prime up to N by repeatedly striking out the multiples of each prime in turn.

Contents

Sieve of Eratosthenes

The Sieve of Eratosthenes is a method, more than two thousand years old, for finding all the primes up to some limit N — not by testing each number, but by elimination. Write down the integers from 2 to N. Circle the first, 2: it is prime. Now cross out every larger multiple of 2. Move to the next surviving number, 3: it is prime, so cross out its multiples. Repeat. Whatever is never crossed out is exactly the set of primes.

It is named for Eratosthenes of Cyrene, the polymath who also measured the circumference of the Earth. The sieve's charm is that it never performs a single division: primality falls out of pure marking.

Watch it run

Below, the integers 2 \dots N are laid in a row. A scanning bar selects each new prime, then sweeps across striking out its multiples. The work shrinks pass by pass — by the time the current prime p satisfies p^2 > N, every composite is already gone.

The sieve in motion over 2…200. The ringed cell is the current prime; the moving marker strikes its multiples. Once p² > N the sieve halts — survivors are all prime. Click anywhere to run it again.

Why it is fast

The sieve's genius is in not repeating work. Two optimizations make it efficient.

  • Start at p^2. When you reach prime p, every multiple 2p, 3p, \dots, (p-1)p was already struck by a smaller prime factor. So the first new multiple to cross out is p^2.
  • Stop at \sqrt{N}. Once p^2 > N, any remaining composite would need a prime factor larger than \sqrt N paired with one smaller — but the smaller factor already eliminated it. Everything left is prime.

Counting the operations gives a running time of about N \ln\ln N — almost linear in N. The doubly-logarithmic factor grows so slowly it is nearly a constant.

\sum_{p \le N}\frac{N}{p} \;\approx\; N\ln\ln N.
Cross-outs per prime, N = 200
Each prime strikes roughly N/p numbers, so the work falls off sharply: 2 does the heavy lifting, and by 11 only a handful of cells remain to cross out.

When the sieve reaches a new prime p, why can it begin crossing out at p² instead of 2p?

See also