Skip to content

Instantly share code, notes, and snippets.

@NicolasFrancaX
Created September 26, 2016 12:24
Show Gist options
  • Save NicolasFrancaX/db5f7cad054294e9a83b34a52bf66a8b to your computer and use it in GitHub Desktop.
Save NicolasFrancaX/db5f7cad054294e9a83b34a52bf66a8b to your computer and use it in GitHub Desktop.
/* (**) Determine the prime factors of a given positive integer.
* Construct a flat list containing the prime factors in ascending order.
* Example:
* * (prime-factors 315)
* (3 3 5 7)
*/
function prime(n) {
if (n < 2) {
return false;
} else if (n == 2) {
return true;
} else if (n % 2 == 0) {
return false;
}
var i = 3;
while(i < n) {
if (n % i == 0)
return false;
i += 2;
}
return true
}
function primeFactors(n) {
var numbers = []
, i = 2;
while (i < n) {
if (n % i == 0 && prime(i))
numbers.push(i);
if (i == 2) {
i++;
} else {
i += 2;
}
}
return numbers;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment