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 10 001st prime number?
function nthPrime(n:number):number {
let primes = [2];
let i = 3;
while (primes.length < n) {
if (isPrime(i)) {
primes.push(i);
}
i += 2;
}
return primes[primes.length - 1];
}
// function that determines if a number is prime
function isPrime(n:number):boolean {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
}
Thoughts:
Prime numbers are a bit boring, there's no series relationship going on so doesn't feel like there's a more efficient way, but maybe there is as we're iterating from 2 to the number in question each time checking for primeness.