Find all primes up to n with a sieve in JavaScript
Intermediate · 4 min read
Testing numbers one at a time is fine when you want to know if a single number is prime. When you need every prime up to a limit, there is a much faster method, more than two thousand years old: the sieve of Eratosthenes. Instead of testing each number, you cross out the ones that can't be prime, and whatever is left standing is prime.
In this tutorial you will write sieve(limit), which returns every prime up to limit. You will see why the crossing-out can start at p * p, and find out which primes do any crossing out at all for a limit of 50. You need to know for loops and arrays. A prime is a whole number above 1 that only divides by 1 and itself.
The idea on paper
Write down the numbers from 2 to 30. Then:
- 2 is the first number not crossed out, so it is prime. Cross out every multiple of 2 after it: 4, 6, 8 and so on.
- The next number not crossed out is 3. It is prime. Cross out 6, 9, 12 and so on.
- The next is 5. Cross out its multiples.
- Keep going. Every number left uncrossed is prime.
No division at all, only counting in steps.
A list of flags
In code, "crossed out" is a flag for each number. A Uint8Array is a list of small whole numbers (0 to 255) that starts filled with zeros. We use index n for the number n, with 0 meaning "not crossed out" and 1 meaning "crossed out, so not prime". It uses one byte per number, which is much less memory than an ordinary array.
const flags = new Uint8Array(5);
console.log(flags.join(' ')); // 0 0 0 0 0
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
32 The sieve of Eratosthenes
fairList every prime up to a limit by striking out multiples instead of testing each candidate. Start each prime's marking at p * p, and work out which primes are ever used as markers for a limit of 50.
Stuck? Three hints, smallest first
- 1. A
Uint8Arrayof flags, one per number, is the whole data structure. - 2. The outer loop only has to reach
p * p <= limit; past that every composite has already been struck out. - 3. Marking can start at
p * pbecause2p, 3p, ... (p-1)pwere each already struck out by a smaller prime.
Step 1: a first sieve
Make limit + 1 flags, so the last index is limit itself. For each number that isn't crossed out, cross out its multiples, starting at 2 * p:
function sieveTry(limit) {
const composite = new Uint8Array(limit + 1);
for (let p = 2; p <= limit; p++) {
if (composite[p]) continue;
for (let m = 2 * p; m <= limit; m += p) composite[m] = 1;
}
const out = [];
for (let n = 2; n <= limit; n++) if (!composite[n]) out.push(n);
return out;
}
console.log(sieveTry(30)); // [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
A composite number is one that isn't prime. continue skips to the next p when the current one was already crossed out. This version is correct. It just does more work than it needs to.
Step 2: start crossing out at p * p
When we reach p = 5, the multiples 10, 15 and 20 are already crossed out: 10 and 20 by 2, and 15 by 3. Every multiple of p smaller than p * p has a smaller prime factor, so it was crossed out earlier. So the inner loop can start at p * p:
for (let m = p * p; m <= limit; m += p) composite[m] = 1;
Starting at 2 * p isn't wrong. It is just wasted work.
Step 3: stop the outer loop at the root
Now look at the outer loop. Once p * p is bigger than limit, the inner loop wouldn't run at all, because it starts past the end. Any composite number still uncrossed would need a factor above its own square root, and that can't happen. So the outer loop can stop at p * p <= limit:
const markers = [];
function sieve(limit) {
if (limit < 2) return [];
const composite = new Uint8Array(limit + 1);
for (let p = 2; p * p <= limit; p++) {
if (composite[p]) continue;
if (limit === 50) markers.push(p);
for (let m = p * p; m <= limit; m += p) composite[m] = 1;
}
const out = [];
for (let n = 2; n <= limit; n++) if (!composite[n]) out.push(n);
return out;
}
The final loop still reads every flag up to limit, so primes above the root, like 47, are collected. markers records which primes did the crossing out, but only for a limit of 50, so other calls don't add to it.
Step 4: which primes did the work?
console.log(sieve(50)); // [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 ]
console.log(markers); // [ 2, 3, 5, 7 ]
The square root of 50 is about 7.07. Only 2, 3, 5 and 7 crossed anything out. The next prime, 11, has 11 times 11 = 121, which is past 50, so it has nothing left to do.
Step 5: small limits and bigger ones
console.log(sieve(0), sieve(1), sieve(2)); // [] [] [ 2 ]
console.log([100, 1000, 10000].map((n) => sieve(n).length)); // [ 25, 168, 1229 ]
console.log(sieve(100000).length); // 9592
console.log(sieve(100000).at(-1)); // 99991
The guard limit < 2 returns an empty list, because there are no primes below 2. at(-1) reads the last item of an array. There are 9592 primes below one hundred thousand, and the largest is 99991.
The full solution
The answer panel builds sieve, lists the primes up to 50 with the primes that did the crossing out, and counts the primes below 100, 1000, 10000 and 100000. The checks underneath confirm every count, the sum of the primes below 100 (1060), and that the sieve agrees with trial division below 200. Press Run to see the output.
const markers = []; // which primes actually did any striking out
function sieve(limit) {
if (limit < 2) return [];
const composite = new Uint8Array(limit + 1);
for (let p = 2; p * p <= limit; p++) {
if (composite[p]) continue; // p was struck out, so it is not prime
if (limit === 50) markers.push(p);
for (let m = p * p; m <= limit; m += p) composite[m] = 1;
}
const out = [];
for (let n = 2; n <= limit; n++) if (!composite[n]) out.push(n);
return out;
}
const isPrime = (n) => {
if (n < 2) return false;
if (n % 2 === 0) return n === 2;
for (let d = 3; d * d <= n; d += 2) if (n % d === 0) return false;
return true;
};
const to50 = sieve(50);
const to100000 = sieve(100000);
const counts = [100, 1000, 10000].map((n) => sieve(n).length);
console.log('primes to 50 :', to50);
console.log('markers used :', markers, '<- nothing above sqrt(50)');
console.log('counts :', counts);
console.log('primes below 1e5:', to100000.length, 'largest:', to100000.at(-1));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('every prime up to 50', to50, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]);
test('the marking loop only ever used 2, 3, 5 and 7', markers, [2, 3, 5, 7]);
test('a limit below 2 has no primes at all', [sieve(0), sieve(1), sieve(2)], [[], [], [2]]);
test('25 primes below 100, 168 below 1000, 1229 below 10000', counts, [25, 168, 1229]);
test('the 25th prime is 97', sieve(100).at(-1), 97);
test('they sum to 1060', sieve(100).reduce((a, b) => a + b, 0), 1060);
test('9592 primes below 100000, from one pass over the flags', to100000.length, 9592);
test('the largest of them is 99991', to100000.at(-1), 99991);
test('and the sieve agrees with trial division below 200', same(sieve(200), sieve(200).filter(isPrime)), true);
The sieve trades memory for time: one byte per candidate buys you every prime in the range for roughly n log log n work, where testing each number separately costs n sqrt(n). The limit here stops at a hundred thousand only because these panels run under an iteration guard; the algorithm itself scales to a million on the same few lines, needing a megabyte of flags to do it.
The two loop bounds are the exercise. The outer loop stops at p * p > limit because any composite left standing would need a factor above its own root, which exercise 31 rules out — that is why nothing above 7 marks anything for a limit of 50. The inner loop starts at p * p rather than 2p because every earlier multiple carries a smaller prime factor and was struck out already. Starting at 2p is not wrong, just wasteful.
Common mistakes
- Making the array
limitlong instead oflimit + 1. The last index is thenlimit - 1, solimititself is never checked. - Stopping the final collecting loop at the square root. Only the crossing-out loop stops there. Every flag still has to be read.
- Starting at 0 or 1. Neither is prime. Start collecting at 2.
Try it yourself
- Change
sieveto return the count instead of the list, then find how many primes there are below 500. - Use
sieve(100)to find the twin primes below 100: pairs like 11 and 13 that differ by 2. - Count how many times
composite[m] = 1runs for a limit of 100, once starting at2 * pand once atp * p.