Emmanuel Akinfulubi

JavaScriptMath

Primes up to 1000: count, sum and twin primes in JavaScript

Intermediate · 4 min read

A prime is a whole number above 1 that only divides by 1 and itself: 2, 3, 5, 7, 11 and so on. To list every prime up to 1000, you could test each number one at a time. There is an older and faster way, invented in ancient Greece and still used today: the sieve of Eratosthenes. It finds primes without doing a single division.

In this tutorial you will build the sieve, then use the list it makes to answer questions: how many primes there are below 1000, what they add up to, which ones come in close pairs, and where the biggest gap between them is. You will also check the sieve against a second method, and test a famous unproven claim about even numbers. You need to know arrays, for loops and %.

How the sieve works

Write the numbers from 2 to 1000 in a list. 2 is prime, so cross out every multiple of 2 after it: 4, 6, 8 and so on. The next number not crossed out is 3, so it is prime; cross out its multiples. The next is 5. Keep going. Every number still standing when you reach it is prime, because if it had a smaller prime factor it would already be crossed out.

Uint8Array

To remember which numbers are crossed out, the code uses a Uint8Array. It is an array of small whole numbers (0 to 255) with a fixed length, and every slot starts at 0. Here 0 means "not crossed out" and 1 means "crossed out".

JavaScript

const marks = new Uint8Array(5);
marks[3] = 1;
console.log(marks); // Uint8Array(5) [ 0, 0, 0, 1, 0 ]

Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.

104 The sieve of Eratosthenes, to a thousand

fair

Sieve the primes up to 1000. Report how many there are, their sum, the twin pairs and the largest gap. Check the sieve against ordinary trial division on every number in range, then use the list to test Goldbach's conjecture up to 200.

Stuck? Three hints, smallest first
  1. 1. Mark multiples of each prime as composite. Start marking at i * i, not i * 2.
  2. 2. Trial division only needs divisors up to Math.sqrt(n), and only odd ones after 2.
  3. 3. A Set makes the membership checks in the last two tests cheap.

Step 1: the sieve

Step 1

const sieve = (limit) => {
  const composite = new Uint8Array(limit + 1);
  const primes = [];
  for (let i = 2; i <= limit; i++) {
    if (!composite[i]) {
      primes.push(i);
      for (let j = i * i; j <= limit; j += i) composite[j] = 1;
    }
  }
  return primes;
};
console.log(sieve(30).join(' ')); // 2 3 5 7 11 13 17 19 23 29

A composite number is one that is not prime. The array has limit + 1 slots so that index 1000 exists. When i is not marked, it is prime: push it, then mark its multiples.

The inner loop starts at i * i, not at i * 2. Every smaller multiple, like 3 * 5 = 15 when i is 5, has a smaller prime factor and was crossed out already. Starting at i * 2 gives the same list and does extra work.

Step 2: count and add them up

Step 2

const add = (a, b) => a + b;
const primes = sieve(1000);
console.log(primes.length, primes[primes.length - 1]); // 168 997
console.log(primes.reduce(add, 0));                     // 76127

There are 168 primes up to 1000. The last is 997, and together they add up to 76127.

Step 3: check the sieve a second way

A good way to trust a result is to get it again by a method that has nothing in common with the first. Trial division tests one number by trying to divide it.

Step 3

const isPrime = (n) => {
  if (!Number.isInteger(n) || 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 primeSet = new Set(primes);
const trialAgrees = (limit) => {
  for (let n = 0; n <= limit; n++) if (isPrime(n) !== primeSet.has(n)) return false;
  return true;
};
console.log(trialAgrees(1000)); // true

isPrime rejects anything below 2, handles even numbers in one line (only 2 is prime), and then tries odd divisors up to the square root. A Set answers "is this in the list?" quickly with has. The two methods agree on all 1001 numbers from 0 to 1000.

Step 4: twin primes

Twin primes are two primes that differ by 2, like 11 and 13.

Step 4

const twins = primes.filter((p, i) => primes[i + 1] === p + 2).map((p) => [p, p + 2]);
console.log(twins.length, twins[0], twins[twins.length - 1]); // 35 [ 3, 5 ] [ 881, 883 ]

filter keeps each prime whose next neighbor in the list is exactly 2 more, and map turns it into a pair. There are 35 pairs. Whether twin primes go on forever is still an open question.

Step 5: the largest gap

Step 5

const largestGap = () => {
  let gap = 0;
  let after = 0;
  for (let i = 1; i < primes.length; i++) {
    const g = primes[i] - primes[i - 1];
    if (g > gap) {
      gap = g;
      after = primes[i - 1];
    }
  }
  return [gap, after];
};
console.log(largestGap()); // [ 20, 887 ]

Compare each prime with the one before it and keep the biggest difference. After 887, the next prime is 907: twenty numbers with no prime at all.

Step 6: Goldbach's conjecture

In 1742, Christian Goldbach guessed that every even number above 2 is the sum of two primes: 4 = 2 + 2, 10 = 3 + 7. Nobody has proved it. You can test it up to 200:

Step 6

const goldbachFailsAt = (limit) => {
  for (let n = 4; n <= limit; n += 2) {
    let found = false;
    for (const p of primes) {
      if (p > n / 2) break;
      if (primeSet.has(n - p)) {
        found = true;
        break;
      }
    }
    if (!found) return n;
  }
  return 0;
};
console.log(goldbachFailsAt(200)); // 0

For each even n, try each prime p and ask whether n - p is prime too. Stopping at n / 2 avoids checking each pair twice. A return of 0 means no even number failed.

The full solution

The answer panel has the sieve, isPrime, the twin pairs, the gap and the Goldbach check, and also compares the count with the estimate 1000 / Math.log(1000), about 145. Press Run to see the output.

The answer

const add = (a, b) => a + b;

const sieve = (limit) => {
  const composite = new Uint8Array(limit + 1);
  const primes = [];
  for (let i = 2; i <= limit; i++) {
    if (!composite[i]) {
      primes.push(i);
      for (let j = i * i; j <= limit; j += i) composite[j] = 1;
    }
  }
  return primes;
};

const isPrime = (n) => {
  if (!Number.isInteger(n) || 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 primes = sieve(1000);
const primeSet = new Set(primes);

const trialAgrees = (limit) => {
  for (let n = 0; n <= limit; n++) if (isPrime(n) !== primeSet.has(n)) return false;
  return true;
};

const twins = primes.filter((p, i) => primes[i + 1] === p + 2).map((p) => [p, p + 2]);

const largestGap = () => {
  let gap = 0;
  let after = 0;
  for (let i = 1; i < primes.length; i++) {
    const g = primes[i] - primes[i - 1];
    if (g > gap) {
      gap = g;
      after = primes[i - 1];
    }
  }
  return [gap, after];
};

// Returns the first even number that is NOT a sum of two primes, or 0 if none.
const goldbachFailsAt = (limit) => {
  for (let n = 4; n <= limit; n += 2) {
    let found = false;
    for (const p of primes) {
      if (p > n / 2) break;
      if (primeSet.has(n - p)) {
        found = true;
        break;
      }
    }
    if (!found) return n;
  }
  return 0;
};

console.log('how many      :', primes.length, 'the last one:', primes[primes.length - 1]);
console.log('the first ten :', primes.slice(0, 10));
console.log('their sum     :', primes.reduce(add, 0));
console.log('trial agrees  :', trialAgrees(1000));
console.log('twin pairs    :', twins.length, twins[0], 'up to', twins[twins.length - 1]);
console.log('largest gap   :', largestGap());
console.log('Goldbach to 200:', goldbachFailsAt(200), '<- zero means it held');
console.log('n / ln n says :', 1000 / Math.log(1000), 'against the real', primes.length);
console.log('tiny limits   :', sieve(10), sieve(2), sieve(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.

9 checks

test('there are 168 primes up to 1000, the last of them 997', [primes.length, primes[primes.length - 1]], [168, 997]);
test('the first ten are the ones you would write down by hand', primes.slice(0, 10), [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
test('they sum to 76127', primes.reduce(add, 0), 76127);
test('trial division agrees with the sieve on every number from 0 to 1000', trialAgrees(1000), true);
test('1 is not prime, nor is 0 or a negative, and 2 is the only even one', [isPrime(1), isPrime(0), isPrime(-7), isPrime(2), isPrime(9)], [false, false, false, true, false]);
test('there are 35 twin prime pairs below 1000, from 3 and 5 to 881 and 883', [twins.length, twins[0], twins[twins.length - 1]], [35, [3, 5], [881, 883]]);
test('the largest gap in range is 20, and it opens straight after 887', largestGap(), [20, 887]);
test('every even number from 4 to 200 is a sum of two primes', goldbachFailsAt(200), 0);
test('the sieve is right at the small limits too, where it must produce nothing', [sieve(10), sieve(2), sieve(1)], [[2, 3, 5, 7], [2], []]);

The sieve does no division at all. It walks up marking multiples, and anything still unmarked when you reach it is prime — because every composite has a prime factor below its square root and was therefore marked already. That is also why the inner loop starts at i * i: every multiple of i below i * i has a smaller prime factor and is already crossed out. Starting at i * 2 gives the same answer and does several times the work.

Uint8Array rather than a plain array is worth a line of explanation: it is allocated once at a fixed size, every slot starts at 0, and there are no holes for the engine to reason about. For a sieve to a million that difference is large. Trial division is here as the independent check — two algorithms with nothing in common agreeing on all 1001 answers is much stronger evidence than either one plus a spot check.

The statistics at the end are the reason to build the list. 168 primes below 1000, against the prime number theorem's estimate of 1000 / ln 1000, about 145 — the estimate is asymptotic and still 14% low here. 35 twin pairs, whose infinitude is unproven. A largest gap of 20 immediately after 887. And Goldbach's conjecture, that every even number above 2 is a sum of two primes, holding for every case up to 200 and unproven since 1742. A sieve to 1000 costs about a thousand operations and lets you look at all of it.

Common mistakes

  • Making the array limit long. Indexes then go up to limit - 1, and the limit itself is never checked.
  • Counting 1 as prime. The sieve and isPrime both start at 2 for this reason.
  • Starting the inner loop at i * 2. The answer is the same, but it repeats work that was already done.

Try it yourself

  1. Sieve to 10000 and count the primes. (The answer is 1229.)
  2. Find every gap of exactly 6 between neighboring primes below 100.
  3. Change goldbachFailsAt to return, for each even number, the first pair of primes that works.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.