Hint: Start sieve with true, mark 0 and 1 false [OK]
Common Mistakes:
Using wrong data type for sieve array
Not marking 0 and 1 as non-prime
Initializing all false instead of true
3. What will be the output primes printed by the following C++ code snippet using Sieve of Eratosthenes for 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 << " ";
}
medium
A. 2 3 4 5 7
B. 2 3 5 7
C. 1 2 3 5 7
D. 2 3 5 7 9
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 B
Quick Check:
Primes up to 10 = 2 3 5 7 [OK]
Hint: Mark multiples starting from i*i to avoid repeats [OK]
Common Mistakes:
Including non-primes like 4 or 9
Printing 1 as prime
Not starting inner loop from i*i
4. Identify the error in the following Sieve of Eratosthenes code snippet and select the fix:
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;
}
}
}
medium
A. Start inner loop from j = i + 1
B. Initialize sieve with false instead of true
C. Change outer loop condition to i * i <= n
D. Remove sieve[0] and sieve[1] assignments
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 C
Quick Check:
Outer loop limit = i*i <= n [OK]
Hint: Outer loop runs till i*i <= n for efficiency [OK]
Common Mistakes:
Running outer loop till n wastes time
Starting inner loop incorrectly
Not marking 0 and 1 false
5. You want to find all prime numbers up to n = 50 using the Sieve of Eratosthenes. After running the sieve, how many primes will be found?