Challenge - 5 Problems
Sieve Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Sieve for n=10
What is the output list of primes printed by this Sieve of Eratosthenes code for n=10?
DSA C
int n = 10; int primes[10]; for(int i = 0; i < n; i++) primes[i] = 1; primes[0] = 0; primes[1] = 0; for(int i = 2; i*i < n; i++) { if(primes[i]) { for(int j = i*i; j < n; j += i) primes[j] = 0; } } for(int i = 2; i < n; i++) { if(primes[i]) printf("%d ", i); }
Attempts:
2 left
💡 Hint
Remember that the sieve marks multiples of primes as not prime.
✗ Incorrect
The sieve marks 4, 6, 8, 9, 10 as not prime. Only 2, 3, 5, 7 remain.
❓ Predict Output
intermediate2:00remaining
Count of primes up to 20
How many primes does the Sieve of Eratosthenes find up to n=20?
DSA C
int n = 20; int primes[20]; for(int i = 0; i < n; i++) primes[i] = 1; primes[0] = 0; primes[1] = 0; for(int i = 2; i*i < n; i++) { if(primes[i]) { for(int j = i*i; j < n; j += i) primes[j] = 0; } } int count = 0; for(int i = 2; i < n; i++) { if(primes[i]) count++; } printf("%d", count);
Attempts:
2 left
💡 Hint
Count primes: 2,3,5,7,11,13,17,19
✗ Incorrect
There are 8 primes less than 20: 2,3,5,7,11,13,17,19.
🔧 Debug
advanced2:00remaining
Identify the error in Sieve implementation
What error does this Sieve of Eratosthenes code produce when run for n=15?
DSA C
int n = 15; int primes[15]; for(int i = 0; i < n; i++) primes[i] = 1; primes[0] = 0; primes[1] = 0; for(int i = 2; i*i < n; i++) { if(primes[i]) { for(int j = i*i; j < n; j += i) primes[j] = 0; } } for(int i = 2; i < n; i++) { if(primes[i]) printf("%d ", i); }
Attempts:
2 left
💡 Hint
Check the loop that initializes the primes array.
✗ Incorrect
The loop runs from i=0 to i<=n which accesses primes[n], out of bounds for array size n.
❓ Predict Output
advanced2:00remaining
Output of Sieve for n=30 with print format
What is the printed output of primes for n=30 using this code?
DSA C
int n = 30; int primes[30]; for(int i = 0; i < n; i++) primes[i] = 1; primes[0] = 0; primes[1] = 0; for(int i = 2; i*i < n; i++) { if(primes[i]) { for(int j = i*i; j < n; j += i) primes[j] = 0; } } for(int i = 2; i < n; i++) { if(primes[i]) printf("%d->", i); } printf("null");
Attempts:
2 left
💡 Hint
Remember 9 and 27 are not primes.
✗ Incorrect
The sieve removes multiples of primes, so 9 and 27 are excluded.
🧠 Conceptual
expert2:00remaining
Why does the inner loop start at i*i in Sieve?
In the Sieve of Eratosthenes, why does the inner loop start marking multiples from i*i instead of 2*i?
Attempts:
2 left
💡 Hint
Think about when multiples less than i*i get marked.
✗ Incorrect
Multiples less than i*i are already marked by smaller primes, so starting at i*i avoids redundant work.
