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 array of primes when running the Sieve of Eratosthenes for n=10?
DSA Javascript
function sieve(n) {
const primes = Array(n + 1).fill(true);
primes[0] = false;
primes[1] = false;
for (let i = 2; i * i <= n; i++) {
if (primes[i]) {
for (let j = i * i; j <= n; j += i) {
primes[j] = false;
}
}
}
return primes.map((isPrime, index) => isPrime ? index : null).filter(x => x !== null);
}
console.log(sieve(10));Attempts:
2 left
💡 Hint
Remember that 1 is not a prime number and multiples of primes are marked false.
✗ Incorrect
The sieve marks non-primes false. For n=10, primes are 2, 3, 5, and 7 only.
🧠 Conceptual
intermediateWhy start crossing out multiples from i*i?
In the Sieve of Eratosthenes, why do we start marking multiples of a prime i from i*i instead of 2*i?
Attempts:
2 left
💡 Hint
Think about what happens to multiples less than i*i.
✗ Incorrect
Multiples less than i*i are already marked by smaller primes, so starting at i*i avoids redundant work.
🔧 Debug
advancedIdentify the error in this sieve implementation
What error will this code produce when run for n=10?
DSA Javascript
function sieve(n) {
const primes = Array(n).fill(true);
primes[0] = false;
primes[1] = false;
for (let i = 2; i * i <= n; i++) {
if (primes[i]) {
for (let j = i * i; j <= n; j += i) {
primes[j] = false;
}
}
}
return primes.map((isPrime, index) => isPrime ? index : null).filter(x => x !== null);
}
sieve(10);Attempts:
2 left
💡 Hint
Check the size of the primes array and the indices accessed.
✗ Incorrect
The array size is n, but code accesses primes[n], which is undefined, causing a TypeError.
❓ Predict Output
advancedOutput of sieve for n=20 with a bug
What is the output of this buggy sieve code for n=20?
DSA Javascript
function sieve(n) {
const primes = Array(n + 1).fill(true);
primes[0] = false;
primes[1] = false;
for (let i = 2; i <= n; i++) {
if (primes[i]) {
for (let j = i * 2; j <= n; j += i) {
primes[j] = false;
}
}
}
return primes.map((isPrime, index) => isPrime ? index : null).filter(x => x !== null);
}
console.log(sieve(20));Attempts:
2 left
💡 Hint
Check where the inner loop starts crossing out multiples.
✗ Incorrect
Starting from i*2 instead of i*i causes some composites like 9 and 15 to remain true incorrectly.
🚀 Application
expertCount primes in a large range efficiently
You want to count how many prime numbers are between 1 and 1,000,000 using the Sieve of Eratosthenes. Which approach is best to optimize memory and speed?
Attempts:
2 left
💡 Hint
Think about memory usage and avoiding unnecessary checks.
✗ Incorrect
Using a boolean array and starting from i*i is the classic efficient sieve. Skipping even numbers after 2 reduces work and memory.
