Skip to content

Commit 9407e5f

Browse files
committed
Added PrimeFactors
1 parent f9bac45 commit 9407e5f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Maths/PrimeFactors.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Modified from:
3+
https://github.com/TheAlgorithms/Python/blob/master/maths/prime_factors.py
4+
*/
5+
6+
const PrimeFactors = (n) => {
7+
// input: n: int
8+
// output: primeFactors: Array of all prime factors of n
9+
const primeFactors = []
10+
for (let i = 2; i <= n; i++) {
11+
if (n % i === 0) {
12+
while (n % i === 0) {
13+
primeFactors.push(i)
14+
n = Math.floor(n / i)
15+
}
16+
}
17+
}
18+
if (n > 1) {
19+
primeFactors.push(n)
20+
}
21+
return primeFactors
22+
}
23+
24+
const main = () => {
25+
// PrimeFactors(100)
26+
// > [ 2, 2, 5, 5 ]
27+
console.log(PrimeFactors(100))
28+
// PrimeFactors(2560)
29+
// > [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 5 ]
30+
console.log(PrimeFactors(2560))
31+
}
32+
33+
main()

0 commit comments

Comments
 (0)