while
loop to iterate over all possible prime factors, starting with 2
.f
, exactly divides n
, add f
to the factors array and divide n
by f
. Otherwise, increment f
by one.const primeFactors = n => {
let a = [],
f = 2;
while (n > 1) {
if (n % f === 0) {
a.push(f);
n /= f;
} else {
f++;
}
}
return a;
};
primeFactors(147); // [3, 7, 7]
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️