Skip to content

Instantly share code, notes, and snippets.

@quassy
Last active February 11, 2016 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quassy/f2807b674c6c01e34c28 to your computer and use it in GitHub Desktop.
Save quassy/f2807b674c6c01e34c28 to your computer and use it in GitHub Desktop.
prime-factors.js
var getPrimeFactors = function (number) {
var i = 2;
var limit = Math.floor(number/2);
var factors = [];
while (i < limit) {
// Check if number is divisible by i, if yes add i to list of factors and repeat
// (There can be multiple prime factors of the same value, e.g. 12=2*2*3)
while (number % i === 0) {
number /= i;
factors.push(i);
console.log("Added factor i = "+i+"; new number to test = "+number);
}
i++;
// Lower the limit so the loop does only run as long as necessary
limit = Math.floor(number/2);
}
// After going through all the lower numbers, the remaining on must be (?) prime
factors.push(number);
console.log("Added factor number = "+number+"; program finished");
return factors;
}
var number = 600851475143;
var array = getPrimeFactors(number);
console.log("Prime factors of "+number+" are "+array);
// should be 71, 839, 1471, 6857 (Wolfram Alpha)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment