Home
DSA Visualizer
Mathematics
Sieve of Eratosthenes
Sieve of Eratosthenes Visualization
The Sieve of Eratosthenes finds all prime numbers up to a specified limit. Step through it in the interactive Sieve of Eratosthenes visualization below.
UP TO 50 · STOP AT √50 ≈ 7
ASSUME ALL PRIME
Assume every number from 2 to 50 is prime, then remove the ones that cannot be. 0 and 1 are out by definition.
Next
2 survived, so it is prime. Start crossing out at 2×2 = 4: anything smaller with a factor of 2 also has a factor below 2 and is already gone.
Limit
Intuition
Instead of checking if each number is prime individually (Trial Division), we can iteratively mark the multiples of each prime number as composite. The numbers that remain unmarked are primes.
Concept
- Idea: Start with 2. Mark all multiples of 2 (4, 6, 8...) as composite. Move to the next unmarked number (3), mark its multiples. Continue until √N.
- Efficiency: Much faster than Trial Division for finding all primes up to N.
- Time Complexity: O(N log log N) - very close to linear!
How Sieve of Eratosthenes Works
Algorithm:
- Create a list of booleans up to N, initialized to True.
- Set 0 and 1 to False.
- Loop
pfrom 2 to√N. - If
isPrime[p]is True:- Mark all multiples of
p(starting fromp*p) as False.
- Mark all multiples of
Sieve of Eratosthenes Visualization, Step by Step
Watch the visualization:
- Solid blue: The current prime, and the multiple of it being crossed out.
- Grey, struck through: Multiples already crossed out (composite).
- Green: Numbers not crossed out yet. Every number still green at the end is prime.
When to Use
- Generating a list of all primes up to a large number (e.g., 10^7).
- Pre-computing primes for multiple queries.
When NOT to Use
- Checking primality for a single very large number (use Miller-Rabin).
- When memory is very limited (requires O(N) space).
How to Identify
"Find all primes up to N", "Sum of primes", "K-th prime number".
Applying for software engineering roles? Free, no sign-up:
AI resume checker: match your resume to the job description
Compare its cost with every other algorithm in the Big O cheat sheet.
