735 B
735 B
title, tags, expertise, author, cover, firstSeen, lastUpdated
| title | tags | expertise | author | cover | firstSeen | lastUpdated |
|---|---|---|---|---|---|---|
| Prime factors of number | math,algorithm | beginner | maciv | blog_images/dark-leaves-3.jpg | 2020-12-28T13:11:01+02:00 | 2020-12-28T13:11:01+02:00 |
Finds the prime factors of a given number using the trial division algorithm.
- Use a
whileloop to iterate over all possible prime factors, starting with2. - If the current factor,
f, exactly dividesn, addfto the factors array and dividenbyf. Otherwise, incrementfby 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]