Complete the code to create an array of boolean values initialized to true.
const sieve: boolean[] = new Array(n + 1).fill([1]);
The sieve array should be initialized with true to mark all numbers as potential primes initially.
Complete the for loop to start crossing out multiples from the first prime number.
for (let i = 2; i <= [1]; i++) {
We only need to check numbers up to the square root of n because larger factors will have smaller complementary factors already checked.
Fix the error in the inner loop to mark multiples of i as non-prime.
for (let j = i * i; j <= n; j += [1]) { sieve[j] = false; }
We increase j by i each time to mark all multiples of i as non-prime.
Fill both blanks to collect all prime numbers from the sieve array.
const primes = []; for (let k = 2; k <= n; k++) { if (sieve[[1]]) { primes.push([2]); } }
We check sieve[k] to see if k is prime, then add k to the primes list.
Fill all three blanks to complete the function that returns all primes up to n.
function sieveOfEratosthenes(n: number): number[] {
const sieve: boolean[] = new Array(n + 1).fill([1]);
for (let i = 2; i <= [2]; i++) {
if (sieve[i]) {
for (let j = i * i; j <= n; j += [3]) {
sieve[j] = false;
}
}
}
const primes = [];
for (let k = 2; k <= n; k++) {
if (sieve[k]) primes.push(k);
}
return primes;
}The sieve array is initialized with true. The outer loop runs up to the square root of n. The inner loop increments by i to mark multiples as false.
