Skip to content
StackDecode
Number theory & mathAnimated

Sieve of Eratosthenes

Cross out multiples of each prime.

Time

O(n log log n)

Extra space

O(n)

Use it for

All primes up to n.

How it works

  1. List the numbers from 2 to n and assume they are all prime.
  2. Take the smallest number not crossed out: it is prime. Cross out all its multiples, starting from p².
  3. Repeat for the next number that is not crossed out. You can stop once p² > n.
  4. Every number left standing is prime. O(n log log n).

Watch it run

Loading animation…