Miscellaneous
Sieve of Eratosthenes
An ancient algorithm for finding all prime numbers up to a given limit .
Algorithm
- Create a boolean array of size , initially all
True - Mark 0 and 1 as not prime
- For each number from 2 to :
- If is still marked prime, mark all multiples of (starting from ) as not prime
- All indices still marked
Trueare prime
Why Start from i²?
When marking multiples of , all multiples less than have already been marked by smaller primes ( by 2, by 3, etc.).
Time Complexity
Derivation: The inner loop runs times for each prime . Total work:
The sum of reciprocals of primes grows as (Meissel-Mertens constant).
Space Complexity
Boolean array to track primality.
Implementation
def sieve(n: int) -> list[bool]:
if n < 2:
return [False] * n
prime = [True] * n
prime[0] = prime[1] = False
for i in range(2, int(n ** 0.5) + 1):
if prime[i]:
for j in range(i * i, n, i):
prime[j] = False
return primeOptimizations
Skip even numbers: Only store odd numbers, halving space.
Segmented sieve: Process in blocks for cache efficiency and to handle larger ranges.
Wheel factorization: Skip multiples of small primes (2, 3, 5) during iteration.