Skip to content

Instantly share code, notes, and snippets.

@jremmen
Last active August 29, 2015 14:16
Show Gist options
  • Save jremmen/ff775efa98e58813fa3b to your computer and use it in GitHub Desktop.
Save jremmen/ff775efa98e58813fa3b to your computer and use it in GitHub Desktop.
js: prime factorization examples
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