Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created December 1, 2011 02:05
Show Gist options
  • Save rwaldron/1412787 to your computer and use it in GitHub Desktop.
Save rwaldron/1412787 to your computer and use it in GitHub Desktop.
Project Euler #10, ~850ms run time
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" );
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