find the nth prime number in typescript

To find the nth prime number in TypeScript, we can use the Sieve of Eratosthenes algorithm. This algorithm works by creating a list of all integers up to a certain limit (in this case, we'll use the limit of n * log(n)), marking all composite numbers (i.e. those that are multiples of primes), and returning the nth unmarked integer.

Here's the code:

index.ts
function nthPrime(n: number): number {
  let limit = Math.ceil(n * Math.log(n));
  let sieve = new Array(limit).fill(true); // assume all integers are prime at first
  sieve[0] = false; // zero is not prime
  sieve[1] = false; // one is not prime

  // mark multiples of primes as composite
  for (let i = 2; i <= Math.sqrt(limit); i++) {
    if (sieve[i]) {
      for (let j = i * i; j < limit; j += i) {
        sieve[j] = false;
      }
    }
  }

  // find the nth unmarked integer
  let count = 0;
  for (let i = 2; i < limit; i++) {
    if (sieve[i]) {
      count++;
      if (count === n) {
        return i;
      }
    }
  }

  // should never happen
  return -1;
}
676 chars
30 lines

This code first initializes a list of integers and assumes all of them to be prime. Then, it marks all the multiples of primes as composite using the Sieve of Eratosthenes algorithm. Finally, it counts the number of unmarked integers until it finds the nth unmarked integer, which is the nth prime number.

Note that we've used the Math.ceil function when calculating the limit because the nth prime number can be larger than n * log(n) due to rounding errors. Thus, rounding up guarantees that we won't miss the nth prime number.

gistlibby LogSnag