The Sieve Of Eratosthenes
๐ Problem Statement
Given an integer , return a list of all prime numbers from 2 to (inclusive) using the Sieve of Eratosthenes algorithm. For example, โ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29].
๐ก Intuition
Instead of checking each number individually (which takes per number), the Sieve marks all multiples of each prime as composite in bulk. Start from the smallest prime (2), mark all its multiples as not prime, then move to the next unmarked number, and repeat. The outer loop only runs up to because any composite number's smallest prime factor must be .
๐ง Approach
- Create a boolean array
is_primeof size , initialized to True. - Set
is_prime[0] = is_prime[1] = False. - For each from 2 to : if
is_prime[i]is True, mark all multiples starting at as False. - Collect all indices where
is_prime[i]is still True.
โก Complexity Analysis
โ from the harmonic series over primes
โ for the boolean sieve array
โ ๏ธ Common Mistakes
- Starting the inner loop from instead of โ the smaller multiples were already marked by earlier primes
- Not marking 0 and 1 as non-prime before collecting results
- Using a list of integers instead of a boolean array โ wastes memory
๐ฏ Final Thoughts
The Sieve of Eratosthenes is the gold standard for generating all primes up to . Understanding why the inner loop starts at (not ) and why the outer loop only goes to is key to grasping its efficiency.