Created
December 1, 2011 02:05
-
-
Save rwaldron/1412787 to your computer and use it in GitHub Desktop.
Project Euler #10, ~850ms run time
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
var // Program setup | |
isPrime = require("./isprime"), | |
start = (new Date()).getTime(), | |
end; | |
var // Program specific | |
ceil = 2e6, | |
total = 2, | |
k = 3; | |
for ( ; k <= ceil; k++ ) { | |
if ( isPrime(k) ) { | |
total += k; | |
} | |
} | |
end = (new Date()).getTime() - start; | |
console.log( (total === 142913828922 && "WIN") || "LOSE" ); | |
console.log( end >= 1000 ? (end/1000) + "s" : end + "ms" ); |
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
function isPrime( num ) { | |
var sqrt = Math.sqrt( num ), | |
i = 3; | |
if ( num === 1 || (num > 2 && (num % 2) === 0) ) { | |
return false; | |
} else { | |
for ( ; i <= sqrt; i = i + 2 ) { | |
if ( num % i === 0 ) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
console.assert( !isPrime(1) ); | |
console.assert( isPrime(2) ); | |
console.assert( isPrime(3) ); | |
console.assert( isPrime(5) ); | |
console.assert( !isPrime(4) ); | |
console.assert( !isPrime(6) ); | |
if ( typeof exports !== "undefined" ) { | |
module.exports = isPrime; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment