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 n
th prime number?
Solution:
function nthPrime(n) {
let arr = [2]
for(let i=3; i<=n*2; i=i+2) {
arr.push(i)
}
let totalPrime = primes(arr);
let nthPrime = count(totalPrime, n)
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(arr, n) {
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);