Emmanuel Akinfulubi

JavaScriptMath

Find the nth prime number in JavaScript

Intermediate · 4 min read

"What is the 1000th prime?" sounds like a quiz question, but it is a good exercise in choosing an approach. The primes run 2, 3, 5, 7, 11, 13 and on forever, so the 1st prime is 2, the 6th is 13, and the 1000th turns out to be 7919.

In this tutorial you will write the nth prime two ways. The first counts upwards, testing each number until it has seen n primes. The second uses a sieve, which is faster but needs to know in advance how far to look. You will use a proven formula for that limit and check that it really is big enough. You should know what a prime is and how trial division and the sieve work.

Two approaches

  • Counting: start at 2, test each number with isPrime, and count the primes you meet. When the count reaches n, return that number. It needs no planning, only patience.
  • Sieving: cross out composites in a list of flags up to some limit, then read off the nth prime that survives. It is fast, but you have to choose the limit before you start, because the list of flags has to be created first.

How big is the nth prime?

Mathematicians have proven a limit. For n of 6 or more, the nth prime is smaller than n * (ln n + ln ln n). Here ln is the natural logarithm, Math.log in JavaScript. You don't need to know why it holds, only that it is a safe size for the sieve. "ln ln n" means the log of the log of n.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

33 The nth prime

fair

Return the nth prime: the 1st is 2, the 6th is 13, the 1000th is 7919. Then get the 10001st a second way, by sieving a range you have argued is big enough.

Stuck? Three hints, smallest first
  1. 1. Counting upwards and testing each candidate needs no size estimate, only patience.
  2. 2. To sieve instead you need an upper bound on the nth prime. For n >= 6, n * (ln n + ln ln n) is one.
  3. 3. Take the n - 1 index of the sieved list, and assert the bound rather than trusting it.

Step 1: count upwards

Put a small isPrime inside the function, then loop from 2 upwards:

Step 1

function nthPrimeByCounting(n) {
  if (!Number.isInteger(n) || n < 1) return NaN;
  const isPrime = (m) => {
    if (m < 2) return false;
    if (m % 2 === 0) return m === 2;
    for (let d = 3; d * d <= m; d += 2) if (m % d === 0) return false;
    return true;
  };
  let seen = 0;
  for (let c = 2; ; c++) if (isPrime(c) && ++seen === n) return c;
}
console.log(nthPrimeByCounting(1), nthPrimeByCounting(6)); // 2 13
console.log(nthPrimeByCounting(1000)); // 7919

The loop for (let c = 2; ; c++) has no end condition, so it would run forever. It stops because return exits the function as soon as the count is reached.

++seen === n adds 1 to seen first, then compares. Because of &&, it only runs when c is prime, so seen counts primes, not every number.

Step 2: guard the input

There is no "0th prime" or "2.5th prime". Without the guard, nthPrimeByCounting(0) would loop forever, because seen starts above 0 after the first prime and never equals 0. Returning NaN says "no answer" clearly:

Step 2

console.log(nthPrimeByCounting(0));   // NaN
console.log(nthPrimeByCounting(2.5)); // NaN

Step 3: the limit for a sieve

Write the formula as a function. For n below 6 it doesn't apply, so use 15, which is past the 5th prime, 11:

Step 3

const bound = (n) => (n < 6 ? 15 : Math.ceil(n * (Math.log(n) + Math.log(Math.log(n)))));
console.log(bound(1000));  // 8841
console.log(bound(10001)); // 114320

Math.ceil rounds up to a whole number, because the list of flags needs a whole-number size. The 1000th prime is 7919, safely below 8841.

Step 4: sieve, and stop at the nth prime

This sieve counts primes as it finds them, and returns as soon as it reaches the nth:

Step 4

function nthPrimeBySieve(n) {
  const limit = bound(n);
  const composite = new Uint8Array(limit + 1);
  let seen = 0;
  for (let p = 2; p <= limit; p++) {
    if (composite[p]) continue;
    if (++seen === n) return p;
    for (let m = p * p; m <= limit; m += p) composite[m] = 1;
  }
  return NaN;
}
console.log(nthPrimeBySieve(1000));  // 7919
console.log(nthPrimeBySieve(10001)); // 104743

Notice the outer loop goes all the way to limit, not to the square root. That is because it also does the counting, and it needs to reach the nth prime, which can be far above the root.

Step 5: what if the limit were too small?

The last line, return NaN, only runs if the loop finishes without reaching the nth prime, meaning the limit was too small. Without it, the function would return undefined. That would still turn into NaN in any later maths, but further from the cause, which makes the bug harder to find.

Don't take the formula on trust. Check it:

Step 5

console.log(bound(10001) > 104743); // true
console.log([6, 7, 25, 100].every((n) => bound(n) > nthPrimeByCounting(n))); // true

every returns true only if the test passes for every item in the list.

The full solution

The answer panel builds both functions, lists the first ten primes, finds the 1000th both ways, and sieves for the 10001st. The checks underneath confirm the values (97 is the 25th prime, 541 the 100th), that both methods agree, and that the bound really was big enough. Press Run to see the output.

The answer

function nthPrimeByCounting(n) {
  if (!Number.isInteger(n) || n < 1) return NaN;
  const isPrime = (m) => {
    if (m < 2) return false;
    if (m % 2 === 0) return m === 2;
    for (let d = 3; d * d <= m; d += 2) if (m % d === 0) return false;
    return true;
  };
  let seen = 0;
  for (let c = 2; ; c++) if (isPrime(c) && ++seen === n) return c;
}

// Rosser and Schoenfeld: p(n) < n * (ln n + ln ln n) for n >= 6.
const bound = (n) => (n < 6 ? 15 : Math.ceil(n * (Math.log(n) + Math.log(Math.log(n)))));

function nthPrimeBySieve(n) {
  const limit = bound(n);
  const composite = new Uint8Array(limit + 1);
  let seen = 0;
  for (let p = 2; p <= limit; p++) {
    if (composite[p]) continue;
    if (++seen === n) return p;
    for (let m = p * p; m <= limit; m += p) composite[m] = 1;
  }
  return NaN;                          // the bound was too small
}

const firstTen = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(nthPrimeByCounting);
const counted1000 = nthPrimeByCounting(1000);      // counted once, reused below
const sieved10001 = nthPrimeBySieve(10001);

console.log('first ten     :', firstTen);
console.log('1000th        :', counted1000, 'and by sieve:', nthPrimeBySieve(1000));
console.log('10001st       :', sieved10001, 'from a sieve of', bound(10001));
console.log('nthPrime(0)   :', nthPrimeByCounting(0));

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('the first prime is 2, and the 6th is 13', [firstTen[0], firstTen[5]], [2, 13]);
test('the first ten', firstTen, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
test('the 25th is 97, the 100th is 541', [nthPrimeByCounting(25), nthPrimeByCounting(100)], [97, 541]);
test('the 1000th is 7919', counted1000, 7919);
test('and both methods agree on it', nthPrimeBySieve(1000), counted1000);
test('the sieve reaches the 10001st: 104743', sieved10001, 104743);
test('and the bound it allocated for really was large enough', bound(10001) > 104743, true);
test('the bound holds all the way down to n = 6', [6, 7, 25, 100].every((n) => bound(n) > nthPrimeByCounting(n)), true);
test('a zero or fractional position has no answer', [Number.isNaN(nthPrimeByCounting(0)), Number.isNaN(nthPrimeByCounting(2.5))], [true, true]);

Counting upwards needs no estimate and is the version to write when you want one prime. Sieving needs a limit before it can allocate, which is the interesting constraint: you cannot sieve for "the 10001st prime" without first bounding where it lives. n (ln n + ln ln n) is a proven bound for n >= 6, and the check above holds it to that rather than taking it on trust.

Note the NaN return when the bound turns out too small. A sieve-based nth prime that silently returns undefined in that case is the kind of bug that only shows up on the input you did not test — and undefined flowing into later arithmetic produces NaN anyway, just further from the cause.

Common mistakes

  • Not guarding n. With 0 or a fraction, the counting loop never stops.
  • Stopping the counting sieve at the root. The nth prime is usually far above the square root of the limit.
  • Guessing the sieve size. A guess that is too small gives NaN or a wrong answer. Use a proven bound and check it.

Try it yourself

  1. Time both functions for n = 10001 with console.time and console.timeEnd. Which is faster?
  2. Find the 100th prime with nthPrimeBySieve and compare it with the counting version.
  3. Change the counting version to return the first n primes as an array.

Keep practising

Newsletter

New writing, when it lands.

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