Algorithms · Visualized
Number Theory: Sieve of Eratosthenes
Number Theory
Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.
Finds all prime numbers up to a limit N very efficiently by starting with all numbers marked as 'potentially prime', then repeatedly crossing out the multiples of each prime found, starting from 2 — since any number that's a multiple of a smaller prime can't itself be prime. Time: O(n log log n) average, O(n log log n) worst; space: O(n) — the boolean array.
Big-O: GCD O(log min(a,b)); sieve O(n log log n).
Sieve of Eratosthenes
Number TheoryFinds all prime numbers up to a limit N very efficiently by starting with all numbers marked as 'potentially prime', then repeatedly crossing out the multiples of each prime found, starting from 2 — since any number that's a multiple of a smaller prime can't itself be prime.
How Sieve of Eratosthenes Works
- Create a boolean array of size N+1, initially marking every number from 2 to N as potentially prime.
- Starting from the first prime (2), mark all of its multiples (4, 6, 8, ...) as not prime.
- Move to the next number still marked as prime, and mark all of its multiples as not prime too — you only need to start crossing out from that number's square, since smaller multiples were already crossed out by smaller primes.
- Repeat this process for every number up to the square root of N (beyond that, all remaining unmarked numbers are guaranteed prime).
- Collect every number still marked 'prime' — that's the complete list of primes up to N.
Sieve of Eratosthenes Worked Example
Input: 30
Start with 2..30 all marked prime. Cross out multiples of 2: 4,6,8,...,30. Next prime 3: cross out 9,15,21,27 (6,12,etc already crossed). Next prime 5: cross out 25 (others already crossed). Next candidate 7: 7²=49>30, stop crossing. Remaining primes: [2,3,5,7,11,13,17,19,23,29].
def sieve(n):
prime = [True] * (n + 1)
prime[0] = prime[1] = False
for p in range(2, int(n ** 0.5) + 1):
if prime[p]:
for m in range(p * p, n + 1, p):
prime[m] = False
return [i for i in range(2, n + 1) if prime[i]]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Sieve of Eratosthenes Time & Space Complexity
When to Use Sieve of Eratosthenes
- Precomputing all primes up to a large bound for use in many number-theory problems at once, much faster than checking each number individually.
- Cryptographic key generation, and any algorithm needing quick prime lookups (e.g. factorization).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.