Challenge - 5 Problems
Sieve Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Sieve for n=10
What is the output of the following C++ code that uses the Sieve of Eratosthenes to find primes up to 10?
DSA C++
#include <iostream> #include <vector> int main() { int n = 10; std::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; } } } for (int i = 2; i <= n; i++) { if (prime[i]) std::cout << i << " "; } return 0; }
Attempts:
2 left
💡 Hint
Remember that 1 is not a prime number and multiples of primes are marked false.
✗ Incorrect
The Sieve marks multiples of each prime starting from its square as not prime. For n=10, primes are 2, 3, 5, and 7.
🧠 Conceptual
intermediateWhy start marking multiples from p*p?
In the Sieve of Eratosthenes, why do we start marking multiples of a prime p from p*p instead of 2*p?
Attempts:
2 left
💡 Hint
Think about when multiples get marked in earlier steps.
✗ Incorrect
Multiples less than p*p are already marked by smaller primes, so starting at p*p avoids redundant work.
🔧 Debug
advancedIdentify the error in this sieve code
What error will this code produce when run for n=10?
DSA C++
#include <iostream> #include <vector> int main() { int n = 10; std::vector<bool> prime(n, 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; } } } for (int i = 2; i <= n; i++) { if (prime[i]) std::cout << i << " "; } return 0; }
Attempts:
2 left
💡 Hint
Check the size of the vector and the indices accessed.
✗ Incorrect
The vector size is n=10, so valid indices are 0 to 9. Accessing prime[10] causes out_of_range error.
❓ Predict Output
advancedOutput of Sieve for n=20 with print of primes count
What is the output of this code that prints all primes up to 20 and then prints the count of primes found?
DSA C++
#include <iostream> #include <vector> int main() { int n = 20; std::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; } } } int count = 0; for (int i = 2; i <= n; i++) { if (prime[i]) { std::cout << i << " "; count++; } } std::cout << "\nCount: " << count << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember that 9, 15, and 20 are not primes.
✗ Incorrect
The primes up to 20 are 2, 3, 5, 7, 11, 13, 17, and 19. Count is 8.
🧠 Conceptual
expertTime complexity of Sieve of Eratosthenes
What is the time complexity of the Sieve of Eratosthenes algorithm for finding all primes up to n?
Attempts:
2 left
💡 Hint
The sieve is faster than n log n but slower than linear.
✗ Incorrect
The Sieve of Eratosthenes runs in O(n log log n) time, which is very efficient for prime generation.
