Javascript BigInt calculate Prime Number

Description

Javascript BigInt calculate Prime Number

function isPrime(p) {
  for (let i = 2n; i * i <= p; i++) {
    if (p % i === 0n) return false;
  }//from   w ww  . jav  a 2 s .c  om
  return true
}

function nthPrime(nth) {
  let maybePrime = 2n
  let prime = 0n

  while (nth >= 0n) {
    if (isPrime(maybePrime)) {
      nth--
      prime = maybePrime
    }
    maybePrime++
  }

  return prime;
}

nthPrime(20n)



PreviousNext

Related