find the nth prime number in javascript

To find the nth prime number, we need to loop through numbers till we get the nth prime number. We can write a function that checks if a number is a prime number and then push all prime numbers into an array. Once we reach the nth prime number, we return that number.

Here's the code:

index.tsx
function isPrime(num) {
  for(let i = 2; i <= Math.sqrt(num); i++) {
    if(num % i === 0) {
      return false;
    }
  }
  return true;
}

function nthPrime(n) {
  let primes = [];
  let num = 2;
  while(primes.length < n) {
    if(isPrime(num)) {
      primes.push(num);
    }
    num++;
  }
  return primes[primes.length-1];
}

// Example usage
console.log(nthPrime(5)); // Output: 11
389 chars
24 lines

First, we define a function isPrime that checks if a number is a prime number. We loop through all numbers from 2 to the square root of num and check if any number divides num without a remainder. If yes, we know it's not a prime number and return false. If we have gone through all the numbers and found no divisor, we know it is a prime number and return true.

Next, we define a function nthPrime that finds and returns the nth prime number. We create an empty array primes to store all prime numbers we find. We loop through all numbers starting from 2 until we have found n prime numbers. For each number, we call the isPrime function to check if it's a prime number. If it is, we push it into the primes array. Once we have found n prime numbers, we return the last element (the nth) from the primes array.

gistlibby LogSnag