Sieve of Eratosthenes Find All Primes in DSA C++ - Time & Space Complexity
We want to understand how the time needed to find all prime numbers up to a limit grows as the limit gets bigger.
How does the number of steps change when we check more numbers?
Analyze the time complexity of the following code snippet.
void sieve(int n) {
vector<bool> prime(n+1, true);
prime[0] = prime[1] = false;
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * p; i <= n; i += p) {
prime[i] = false;
}
}
}
}
This code marks all prime numbers up to n by crossing out multiples of each prime.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner loop crosses out multiples of each prime number.
- How many times: The outer loop runs roughly up to the square root of n, and the inner loop runs fewer times as p grows.
As n grows, the number of operations grows a bit faster than n but much slower than n squared.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 to 30 steps |
| 100 | About 300 to 400 steps |
| 1000 | About 5000 to 6000 steps |
Pattern observation: The steps grow roughly like n times the logarithm of the logarithm of n, which is slower than n log n but faster than n.
Time Complexity: O(n log log n)
This means the time grows a bit faster than n but much slower than n squared, making it efficient for large n.
[X] Wrong: "The inner loop runs n times for each number, so the time is O(n²)."
[OK] Correct: The inner loop starts at p squared and skips multiples, so it runs fewer times as p grows, reducing total steps significantly.
Understanding this algorithm shows you can analyze loops that don't run the same number of times each iteration, a useful skill for many problems.
"What if we started crossing out multiples from 2*p instead of p*p? How would the time complexity change?"
Practice
Sieve of Eratosthenes algorithm?Solution
Step 1: Understand the algorithm's goal
The Sieve of Eratosthenes is designed to identify prime numbers efficiently.Step 2: Recognize the output
It marks multiples of primes as non-prime, leaving primes unmarked up to the limit.Final Answer:
To find all prime numbers up to a given limit -> Option DQuick Check:
Sieve finds primes = D [OK]
- Confusing sieve with sorting algorithms
- Thinking it calculates factorial or gcd
- Assuming it finds primes beyond the limit
n?Solution
Step 1: Check initialization for prime marking
The sieve should start with all true except 0 and 1, which are not prime.Step 2: Validate code correctness
std::vector<bool> sieve(n+1, true); sieve[0] = sieve[1] = false; uses a vector<bool> with size n+1, sets all true, then marks 0 and 1 false correctly.Final Answer:
std::vector<bool> sieve(n+1, true); sieve[0] = sieve[1] = false; -> Option AQuick Check:
Initialize sieve true except 0,1 false = A [OK]
- Using wrong data type for sieve array
- Not marking 0 and 1 as non-prime
- Initializing all false instead of true
n = 10?
int n = 10;
std::vector<bool> sieve(n+1, true);
sieve[0] = sieve[1] = false;
for (int i = 2; i * i <= n; i++) {
if (sieve[i]) {
for (int j = i * i; j <= n; j += i) {
sieve[j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (sieve[i]) std::cout << i << " ";
}Solution
Step 1: Run sieve marking multiples
Multiples of 2 (4,6,8,10) and 3 (9) are marked false.Step 2: Identify primes left true
Numbers 2, 3, 5, 7 remain true and are printed.Final Answer:
2 3 5 7 -> Option BQuick Check:
Primes up to 10 = 2 3 5 7 [OK]
- Including non-primes like 4 or 9
- Printing 1 as prime
- Not starting inner loop from i*i
int n = 20;
std::vector<bool> sieve(n+1, true);
sieve[0] = sieve[1] = false;
for (int i = 2; i <= n; i++) {
if (sieve[i]) {
for (int j = i * 2; j <= n; j += i) {
sieve[j] = false;
}
}
}Solution
Step 1: Analyze loop conditions
The outer loop runs up to n, which is inefficient and unnecessary.Step 2: Correct loop to optimize marking
Changing outer loop to run while i * i <= n avoids redundant checks and improves performance.Final Answer:
Change outer loop condition to i * i <= n -> Option CQuick Check:
Outer loop limit = i*i <= n [OK]
- Running outer loop till n wastes time
- Starting inner loop incorrectly
- Not marking 0 and 1 false
n = 50 using the Sieve of Eratosthenes. After running the sieve, how many primes will be found?Solution
Step 1: List primes up to 50
Primes are: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47 (total 15).Step 2: Count primes correctly
Counting carefully confirms total primes up to 50 is 15.Final Answer:
15 -> Option AQuick Check:
Count primes ⤠50 = 15 [OK]
- Counting non-primes like 1 or 9
- Including primes beyond 50
- Miscounting total primes
Ready to prove it?
Pass the test and this pattern moves unknown
