Lesson 7 of 15
Sieve of Eratosthenes
Sieve of Eratosthenes
When you need all primes up to some limit , running individual primality tests is inefficient. The Sieve of Eratosthenes (attributed to the Greek mathematician Eratosthenes, ~240 BCE) generates all primes up to in time.
The Algorithm
- Create a boolean array
is_prime[0..n], initially allTrue - Mark
is_prime[0] = is_prime[1] = False - For each from 2 to : if
is_prime[i]isTrue, mark all multiples of starting from asFalse - Collect all indices where
is_prime[i]isTrue
def sieve(n):
if n < 2:
return []
is_p = [True] * (n + 1)
is_p[0] = is_p[1] = False
for i in range(2, int(n**0.5) + 1):
if is_p[i]:
for j in range(i*i, n+1, i):
is_p[j] = False
return [i for i in range(2, n+1) if is_p[i]]
print(sieve(20)) # [2, 3, 5, 7, 11, 13, 17, 19]
Why Start from ?
When we reach , all composites of the form where have already been marked by earlier primes. So we start at , saving significant work.
Time & Space Complexity
| Method | Time per query | Space |
|---|---|---|
| Trial division (one number) | ||
| Sieve (all primes up to ) | total |
The sieve wins when you need many primes. It is the go-to algorithm for primes up to .
Your Task
Implement sieve(n) that returns a list of all primes up to and including .
Python runtime loading...
Loading...
Click "Run" to execute your code.