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
- List the numbers from 2 to n and assume they are all prime.
- Take the smallest number not crossed out: it is prime. Cross out all its multiples, starting from p².
- Repeat for the next number that is not crossed out. You can stop once p² > n.
- Every number left standing is prime. O(n log log n).
Watch it run
Loading animation…