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 Java code that uses the Sieve of Eratosthenes to find all primes up to 10?
Note: The output prints primes separated by spaces.
Note: The output prints primes separated by spaces.
DSA Java
public class Main { public static void main(String[] args) { int n = 10; boolean[] prime = new boolean[n + 1]; for (int i = 2; i <= n; i++) { prime[i] = true; } 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]) { System.out.print(i + " "); } } } }
Attempts:
2 left
💡 Hint
Remember, the sieve marks multiples of primes as not prime.
✗ Incorrect
The sieve marks all multiples of each prime starting from its square as false. For n=10, primes are 2, 3, 5, and 7 only.
❓ Predict Output
intermediateNumber of primes up to 20
How many prime numbers does the following Sieve of Eratosthenes code find up to 20?
DSA Java
public class Main { public static void main(String[] args) { int n = 20; boolean[] prime = new boolean[n + 1]; for (int i = 2; i <= n; i++) { prime[i] = true; } 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]) { count++; } } System.out.println(count); } }
Attempts:
2 left
💡 Hint
Count primes: 2,3,5,7,11,13,17,19
✗ Incorrect
The primes up to 20 are 2,3,5,7,11,13,17,19 which total 8.
🔧 Debug
advancedIdentify the error in Sieve implementation
What error will the following Java code produce when run?
DSA Java
public class Main { public static void main(String[] args) { int n = 15; boolean[] prime = new boolean[n]; for (int i = 2; i <= n; i++) { prime[i] = true; } 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]) { System.out.print(i + " "); } } } }
Attempts:
2 left
💡 Hint
Check array size and indexing carefully.
✗ Incorrect
The boolean array is of size n (15), but indices go up to n (15), which is out of bounds since valid indices are 0 to 14.
🧠 Conceptual
advancedWhy 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 from p*p avoids redundant work.
🚀 Application
expertFind the 10th prime using Sieve
Using the Sieve of Eratosthenes, what is the 10th prime number?
Attempts:
2 left
💡 Hint
List primes in order: 2,3,5,7,11,13,17,19,23,29...
✗ Incorrect
The first 10 primes are 2,3,5,7,11,13,17,19,23,29. The 10th prime is 29.
