Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a boolean array to mark primes up to n.
DSA C#
bool[] isPrime = new bool[[1]];Attempts:
3 left
💡 Hint
Common Mistakes
Using size n misses the number n itself.
Using n - 1 causes index out of range for n.
✗ Incorrect
We need an array from 0 to n inclusive, so size is n + 1.
2fill in blank
mediumComplete the code to initialize all numbers as prime except 0 and 1.
DSA C#
for (int i = 2; i < [1]; i++) isPrime[i] = true;
Attempts:
3 left
💡 Hint
Common Mistakes
Looping only to n misses initializing the last number.
Looping to n - 1 misses numbers near n.
✗ Incorrect
We initialize primes up to n inclusive, so loop until n + 1.
3fill in blank
hardFix the error in the loop condition to stop at the square root of n.
DSA C#
for (int i = 2; i <= [1]; i++)
Attempts:
3 left
💡 Hint
Common Mistakes
Looping to n is inefficient.
Looping to n / 2 is more than needed.
✗ Incorrect
We only need to check primes up to the square root of n.
4fill in blank
hardFill both blanks to mark multiples of i as not prime starting from i*i.
DSA C#
for (int j = i * i; j < [1]; j += [2]) isPrime[j] = false;
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from i instead of i*i marks wrong numbers.
Using wrong step size skips some multiples.
✗ Incorrect
We mark multiples from i*i up to n inclusive, stepping by i.
5fill in blank
hardFill all three blanks to collect all primes into a list.
DSA C#
List<int> primes = new List<int>(); for (int k = 2; k < [1]; k++) { if (isPrime[[2]]) { primes.[3](k); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong loop limit misses last prime.
Using wrong index inside isPrime causes errors.
Using wrong method name instead of Add.
✗ Incorrect
Loop through 2 to n inclusive, check isPrime[k], and add k to primes list.
