Back to Freecodecamp

Challenge 81: Nth Prime

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd63.md

latest1.1 KB
Original Source

--description--

A prime number is a positive integer greater than 1 that is divisible only by 1 and itself. The first five prime numbers are 2, 3, 5, 7, and 11.

Given a positive integer n, return the nth prime number. For example, given 5 return the 5th prime number: 11.

--hints--

nthPrime(5) should return 11.

js
assert.equal(nthPrime(5), 11);

nthPrime(10) should return 29.

js
assert.equal(nthPrime(10), 29);

nthPrime(16) should return 53.

js
assert.equal(nthPrime(16), 53);

nthPrime(99) should return 523.

js
assert.equal(nthPrime(99), 523);

nthPrime(1000) should return 7919.

js
assert.equal(nthPrime(1000), 7919);

--seed--

--seed-contents--

js
function nthPrime(n) {

  return n;
}

--solutions--

js
function nthPrime(n) {
  const primes = [];
  let num = 2;

  while (primes.length < n) {
    let isPrime = true;
    for (let i = 2; i * i <= num; i++) {
      if (num % i === 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) primes.push(num);
    num++;
  }

  return primes[n - 1];
}