Add primeFactors
This commit is contained in:
committed by
Chalarangelo
parent
720d7a8f1c
commit
414e374ab4
29
snippets/primeFactors.md
Normal file
29
snippets/primeFactors.md
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
---
|
||||||
|
title: primeFactors
|
||||||
|
tags: math,algorithm,beginner
|
||||||
|
---
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
```js
|
||||||
|
const primeFactors = n => {
|
||||||
|
let a = [],
|
||||||
|
f = 2;
|
||||||
|
while (n > 1) {
|
||||||
|
if (n % f === 0) {
|
||||||
|
a.push(f);
|
||||||
|
n /= f;
|
||||||
|
} else {
|
||||||
|
f++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
primeFactors(147); // [3, 7, 7]
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user