-
-
Save jayrbolton/435074c1771f7a7ac761 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// project euler #7 | |
// | |
// 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? | |
// Approach I came up with after a while: | |
// - I remembered Sieve of Eratosthenes but couldn't figure out the exact idea without lazy lists | |
// - So instead I just keep track of all the previous primes and test the modulo on each prime in every loop | |
// - Only iterate on odd numbers, easy elimination of half the set | |
function nthPrime(limit) { | |
var primes = [2, 3], current = 5 | |
for(var i = 3; i <= limit; current += 2) { | |
var isPrime = true | |
for(var j = 0; j < primes.length && isPrime; ++j) { | |
isPrime = current % primes[j] !== 0 | |
} | |
if(isPrime) { | |
primes.push(current) | |
++i | |
} | |
} | |
return primes[primes.length - 1] | |
} | |
module.exports = nthPrime | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment