Last active
August 29, 2015 14:16
-
-
Save jremmen/ff775efa98e58813fa3b to your computer and use it in GitHub Desktop.
js: prime factorization examples
This file contains 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
prime_factorization = function(n) { | |
var i = 2; | |
var factors = []; | |
while (n > 0 && i <= n) { | |
while (n % i == 0) { | |
factors.push(i); | |
n = n / i; | |
} | |
i++; | |
} | |
return factors; | |
} | |
prime_factorization = function(n) { | |
function factor(n, i, acc) { | |
if (n == 1) return acc; | |
else | |
if (n % i == 0) | |
return factor(n / i, i, acc.concat([i])); | |
else | |
return factor(n, ++i, acc); | |
} | |
return factor(n, 2, []); | |
} | |
prime_factorization = function(n) { | |
if (n == 1) return []; | |
else return factor(2, []); | |
function factor(i) { | |
if (n % i == 0) return [i].concat(prime_factorization(n / i)); | |
else return factor(++i); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment