# Prime factors of number

JavaScript, Math, Algorithm · Dec 28, 2020 Finds the prime factors of a given number using the trial division algorithm.

• Use a `while` loop to iterate over all possible prime factors, starting with `2`.
• If the current factor, `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]`

## More like this

• ### JavaScript Algorithms

Learn a handful of popular algorithms, implemented in JavaScript ES6.

Collection · 35 snippets

• ### Primes up to given number

Generates primes up to a given number, using the Sieve of Eratosthenes.

JavaScript, Math · Dec 28, 2020

• ### Quotient and module of division

Returns an array consisting of the quotient and remainder of the given numbers.

JavaScript, Math · Oct 7, 2020

• ### Factorial of number

Calculates the factorial of a number.

JavaScript, Math · Dec 28, 2020