1. Assume all prime
Start by assuming every number is prime, then cross out composites.
const isPrime = new Array(n + 1).fill(true)Typorithm · medium
Step 1 of 8 · intro card
Math & Number Theory
Mark every number prime, then cross out multiples of each prime starting at its square.
Instead of testing each number, the sieve eliminates composites in bulk.
For each prime i, all multiples from i*i upward are crossed out — smaller ones already are.
Sieving only up to sqrt(n) suffices, since any composite has a factor at most sqrt(n).
Start crossing out at i*i.
Sieve i only up to sqrt(n).
Survivors are prime.
function sieve(n) {
const isPrime = new Array(n + 1).fill(true);
isPrime[0] = false;
isPrime[1] = false;
for (let i = 2; i * i <= n; i += 1) {
if (isPrime[i]) {
for (let j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
const primes = [];
for (let i = 2; i <= n; i += 1) {
if (isPrime[i]) primes.push(i);
}
return primes;
}Connect each part of the code to the concept before you type.
Start by assuming every number is prime, then cross out composites.
const isPrime = new Array(n + 1).fill(true)Only sieve from primes up to sqrt(n); larger ones are already marked.
for (let i = 2; i * i <= n; i += 1)Smaller multiples of i were already crossed out by smaller primes.
for (let j = i * i; j <= n; j += i)Mark each multiple of i as composite.
isPrime[j] = falseWhatever stays true is prime.
if (isPrime[i]) primes.push(i)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputPrimes up to 20
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state