Skip to content

Instantly share code, notes, and snippets.

@clauswitt
Created May 29, 2010 19:11
Show Gist options
  • Save clauswitt/418464 to your computer and use it in GitHub Desktop.
Save clauswitt/418464 to your computer and use it in GitHub Desktop.
var sys = require('sys');
var Euler3 = 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 getLargestPrimeFactor = function(ofNum) {
for(var i=2;i<Math.round(ofNum/2);i++) {
if(isDivisor(ofNum, i)) {
candidate = ofNum/i;
if(isPrimeNumber(candidate)) {
sys.puts('Result: ' + candidate);
break;
}
}
}
}
getLargestPrimeFactor(600851475143);
};
new Euler3();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment