Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create an array of boolean values initialized to true.
DSA Javascript
const sieve = new Array(n + 1).fill([1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using false instead of true will mark all numbers as non-prime initially.
Using 0 or null will not correctly represent prime status.
✗ Incorrect
We fill the array with true because initially we assume all numbers are prime.
2fill in blank
mediumComplete the code to start crossing out multiples from the square of the current prime candidate.
DSA Javascript
for (let j = [1]; j <= n; j += i) { sieve[j] = false; }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from i + i crosses out some numbers multiple times.
Starting from i - 1 or 2 * i is incorrect for the sieve algorithm.
✗ Incorrect
We start crossing out multiples from i squared because smaller multiples were already crossed out by smaller primes.
3fill in blank
hardFix the error in the loop condition to only check up to the square root of n.
DSA Javascript
for (let i = 2; i <= [1]; i++) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using n or n/2 causes unnecessary checks and slows down the algorithm.
Using n * n is incorrect and causes errors.
✗ Incorrect
We only need to check up to the square root of n because any composite number must have a factor less than or equal to its square root.
4fill in blank
hardFill both blanks to collect all prime numbers from the sieve array.
DSA Javascript
const primes = []; for (let i = 2; i <= n; i++) { if (sieve[[1]]) { primes.push([2]); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using n instead of i causes wrong indexing or adding wrong numbers.
Using true instead of i in push adds a boolean instead of the prime number.
✗ Incorrect
We check sieve[i] to see if i is prime, and if so, add i to the primes list.
5fill in blank
hardFill all three blanks to complete the Sieve of Eratosthenes function that returns all primes up to n.
DSA Javascript
function sieveOfEratosthenes(n) {
const sieve = new Array(n + 1).fill([1]);
sieve[0] = false;
sieve[1] = false;
for (let i = 2; i <= [2]; i++) {
if (sieve[i]) {
for (let j = i * i; j <= [3]; j += i) {
sieve[j] = false;
}
}
}
const primes = [];
for (let i = 2; i <= n; i++) {
if (sieve[i]) primes.push(i);
}
return primes;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing sieve with false causes no primes to be found.
Looping up to n instead of square root of n is inefficient.
Using false in the inner loop condition causes logic errors.
✗ Incorrect
We initialize sieve with true, loop up to square root of n, and use n in the inner loop condition.
