Skip to content

Instantly share code, notes, and snippets.

@bencoveney
Created June 15, 2014 17:52
Show Gist options
  • Save bencoveney/1b49a942e89e462cfea5 to your computer and use it in GitHub Desktop.
Save bencoveney/1b49a942e89e462cfea5 to your computer and use it in GitHub Desktop.
Summation of primes
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 findPrimesBelow = function(limit) {
var currentPrimes = [];
var iterator = 2; //begins at 2, the first prime
// loop until the limit has been reached
while(iterator < limit)
{
if(iterator % 1000 === 0)
{
console.log(iterator);
}
// test if the current number is prime
if(isPrime(iterator, currentPrimes))
{
currentPrimes.push(iterator);
}
// advance the iterator
iterator++;
}
return currentPrimes;
}
// find the primes
var primes = findPrimesBelow(2000000);
// sum them
var sum = 0;
for(var i = 0; i < primes.length; i++)
{
sum += primes[i];
}
console.log(sum);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment