Created
June 15, 2014 17:09
-
-
Save bencoveney/37133739b2ce715261b5 to your computer and use it in GitHub Desktop.
10001st prime
This file contains 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
var isPrime = function(number, primes) { | |
// Is the number evenly divisible by any of the current primes? | |
for(var i = 0; i < primes.length; i++) | |
{ | |
if(number % primes[i] === 0) | |
{ | |
// if we manage an even division the number isnt prime | |
return false; | |
} | |
} | |
// If no even division has been found the number is prime | |
return true; | |
} | |
var findPrime = function(primeToFind) { | |
var currentPrimes = []; | |
var iterator = 2; //begins at 2, the first prime | |
// loop until the desired prime has been found | |
while(currentPrimes.length < primeToFind) | |
{ | |
// test if the current number is prime | |
if(isPrime(iterator, currentPrimes)) | |
{ | |
currentPrimes.push(iterator); | |
} | |
// advance the iterator | |
iterator++; | |
} | |
return currentPrimes[primeToFind-1]; | |
} | |
console.log(findPrime(10001)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment