Last active
February 11, 2016 11:40
-
-
Save quassy/f2807b674c6c01e34c28 to your computer and use it in GitHub Desktop.
prime-factors.js
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 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