Coding Interview Prep: Project Euler - Ten Thousand First Prime Number (freeCodeCamp)

 Problem 7: 10001st prime

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the nth prime number?


Solution:


function nthPrime(n) {
  let arr = [2]
  for(let i=3i<=n*2i=i+2) {
    arr.push(i)
  }
  let totalPrime = primes(arr);
  let nthPrime = count(totalPrimen)
  console.log(nthPrime)
  return nthPrime;
}

function primes(arr) {
  let arrs = arr;  
  for(let i=0;i<arrs.length;i++) {
    for(let j=arrs.length-1;j>i;j--) {
      if(arrs[j]%arrs[i] == 0) {
        arrs = arrs.filter(item => item !== arrs[j])
      }
    }
  }
  return arrs;
}

function count(arrn) {
  let length = arr.length;
  let p = arr
  while(length <= n) {
    let newlimit = p[length-1] + length
    for(let i=p[length-1]; i<=newlimit;) {
      i++;
      p.push(i)
    }  
    p = primes(p)
    length = p.length
  }

  return p[n-1]
}

nthPrime(100);

ten thousand first prime number

Click here to go to the original link of the question.

Post a Comment

Previous Post Next Post