Skip to content

Instantly share code, notes, and snippets.

@binodpanta
Last active December 19, 2015 11:18
Show Gist options
  • Save binodpanta/5946216 to your computer and use it in GitHub Desktop.
Save binodpanta/5946216 to your computer and use it in GitHub Desktop.
// An attempt to solve the sum of primes problems posted at http://projecteuler.net/problem=10
// References: http://stackoverflow.com/questions/15750574/js-prime-numbers-script-explanation
// Runs in about 89.4s on my Windows dual-core laptop, Win 7, Intel Core 2 Duo (x2GHz), 4GB RAM, using nodejs
// My output:
// 142913828922
// primes found 148933
// [Finished in 89.4s]
// Verified against answer on projecteuler.net
// Summary: build up a list of primes as you go, check each number if it is divisible by the primes in that list
// A prime number is not divisible by any primes less than itself
var sum = 2;
var num = 2000000;
var starter = num; if (num%2===0) starter = num-1;
// to store cumulative list of primes
var listofprimes = [2];
var isprimeforOdd = function (x) {
for (var i=0;i<listofprimes.length;i++) {
var cur = listofprimes[i];
if (x % cur == 0) return false; // not a prime since we found a prime divisor
}
return true;
};
for (var i = 3; i <= starter; i+=2) {
// even numbers out the door!
if (isprimeforOdd(i)) {
listofprimes.push(i); sum+=i;
}
}
console.log(sum);
console.log('primes found ' + listofprimes.length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment