Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the boolean array for marking primes.
DSA Java
boolean[] isPrime = new boolean[[1] + 1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using size n instead of n+1 causes index errors.
Forgetting that array indices start at 0.
✗ Incorrect
The array size must be n+1 to include the number n itself.
2fill in blank
mediumComplete the code to mark all numbers as initially prime.
DSA Java
for (int i = 2; i <= [1]; i++) { isPrime[i] = true; }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting loop from 0 or 1.
Looping beyond n.
✗ Incorrect
We mark all numbers from 2 to n as true initially.
3fill in blank
hardFix the error in the loop condition to stop at the square root of n.
DSA Java
for (int i = 2; i <= [1]; i++) { if (isPrime[i]) { for (int j = i * i; j <= n; j += i) { isPrime[j] = false; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Looping all the way to n wastes time.
Using n/2 or n-1 is unnecessary.
✗ Incorrect
We only need to check up to the square root of n for efficiency.
4fill in blank
hardFill both blanks to print all prime numbers after sieve completion.
DSA Java
for (int i = [1]; i <= [2]; i++) { if (isPrime[i]) { System.out.print(i + " "); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from 0 or 1 which are not primes.
Stopping before n.
✗ Incorrect
Prime numbers start from 2 up to n.
5fill in blank
hardFill all three blanks to complete the Sieve of Eratosthenes method.
DSA Java
public static void sieve(int [1]) { boolean[] isPrime = new boolean[[2] + 1]; for (int i = 2; i <= [3]; i++) { isPrime[i] = true; } for (int i = 2; i <= (int) Math.sqrt([1]); i++) { if (isPrime[i]) { for (int j = i * i; j <= [1]; j += i) { isPrime[j] = false; } } } for (int i = 2; i <= [1]; i++) { if (isPrime[i]) { System.out.print(i + " "); } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causing errors.
Incorrect array size or loop limits.
✗ Incorrect
All blanks represent the input number n to define array size, loop limits, and checks.
