Skip to content

Instantly share code, notes, and snippets.

@clauswitt
Created July 4, 2011 18:47
Show Gist options
  • Select an option

  • Save clauswitt/1063766 to your computer and use it in GitHub Desktop.

Select an option

Save clauswitt/1063766 to your computer and use it in GitHub Desktop.
Euler7.js
var sys = require('sys');
var Euler7 = function() {
var isPrimeNumber = function(num) {
//1 is NOT a prime number
if(num == 1) return false;
//2 is a prime number.
if(num == 2) return true;
//Exit early for even numbers (except 2 which is the only equal prime number).
if((num % 2)==0) {
return false;
}
//There is no reason to check numbers above the square root of the number. The reason is that if a divisor above the square root exists, one below will as well.
for(var i=2;i<=Math.sqrt(num);i++) {
if(isDivisor(num,i)) {
return false;
}
}
//If no divisors was found the number must be a prime.
return true;
}
var isDivisor = function(number, candidate) {
//If a division has no remainder the candidate is a divisor of number.
return ((number%candidate)==0);
}
var getResult = function(primeCountNumber) {
internalPrimeCount = 0;
result = 0;
for(var i=1;i<40000000;i++) {
if(isPrimeNumber(i)) {
internalPrimeCount++;
if(internalPrimeCount==primeCountNumber) {
result = i;
break;
}
}
}
sys.puts('Result: ' + result);
}
getResult(10001);
};
new Euler7();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment