Sieve of Eratosthenes
Problem Statement:ā
Given a positive integer n , calculate and return all prime numbers less than or equal to n using the Sieve of Eratosthenes algorithm.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
-
Example:
Given a positive integer
n
, calculate and return all prime numbers less than or equal to
n
using the
Sieve of Eratosthenes
algorithm.
A
prime number
is a natural number greater than 1 that has no positive divisors other than 1 and itself.
ā Solution: Sieve of Eratosthenes (Prime Generation)ā
class Solution {
public:
vector<int> sieve(int n) {
vector<bool> prime(n + 1, true); // mark all as prime initially
vector<int> res;
// Start marking from 2 to n
for(int p = 2; p <= n; p++){
if(prime[p]){
// Mark all multiples of p as not prime
for(int i = p * p; i <= n; i += p){
prime[i] = false;
}
}
}
// Collect all primes into result vector
for(int i = 2; i <= n; i++){
if(prime[i]) res.push_back(i);
}
return res;
}
};
š How It Worksā
- Initializes a boolean array
prime[]of sizen+1with alltrue. - Starts iterating from
2ton. For every number marked astrue, it marks all multiples of that number asfalse(i.e., not prime). - Begins inner loop from
p * pinstead of2 * pfor optimization. - Finally, all numbers left as
truein the array are collected into the result vector and returned.
š§© Key Formula / Recurrenceā
-
For each prime
p, mark:prime[p * p], prime[p * p + p], prime[p * p + 2p], ... <= nas not prime.
ā±ļø Time & Space Complexityā
| Metric | Value |
|---|---|
| ā±ļø Time | O(n log log n) |
| š¾ Space | O(n) |
ā ļø Edge Casesā
n < 2ā returns empty list (no primes).- Handles up to large values like
10ā¶efficiently.
š” Other Approachesā
| Approach | Time Complexity |
|---|---|
| Basic primality check | O(nān) ā |
| Sieve of Eratosthenes | O(n log log n) ā
|
š Related Problemsā
- Count Primes (Leetcode 204)
- Segmented Sieve (for large ranges)
- Smallest Prime Factor (SPF) array
- Euler's Totient Function (Ļ)
š¬