Skip to content

Commit 799bb6d

Browse files
Added Prime Factors Program
1 parent d18bcda commit 799bb6d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Maths/PrimeFactors.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//Prime Factorise a Natural Number into its Prime Factors (Issue #54)
2+
//https://github.com/akshitagit/JavaScript/issues/54
3+
//Contributed by @tauseefmohammed2 : https://github.com/tauseefmohammed2
4+
5+
function PrimeFactors (number) {
6+
7+
//Storing All Prime Factors in the Array : primeFactors
8+
var primeFactors = [];
9+
10+
//Checking Whether 2 is a Factor of Input Number
11+
while (number % 2 === 0) {
12+
primeFactors.push(2);
13+
number = number / 2;
14+
}
15+
16+
//Storing Square Root in Variable : sqrtNumber
17+
var sqrtNumber = Math.sqrt(number);
18+
19+
//Finding all Factors Between 3 and sqrtNumber
20+
for (var i = 3; i <= sqrtNumber; i++) {
21+
while (number % i === 0) {
22+
primeFactors.push(i);
23+
number = number / i;
24+
}
25+
}
26+
27+
//If the Input Number is Still Greater than 2, Then Push the Number itself in the Prime Factors Array
28+
if (number > 2) {
29+
primeFactors.push(number);
30+
}
31+
32+
//Returning the Array of Prime Factors
33+
return primeFactors;
34+
}
35+
36+
console.log(PrimeFactors(50)); //Output : [2,5,5]
37+
console.log(PrimeFactors(17)); //Output : [17]
38+
console.log(PrimeFactors(100)); //Output : [2,2,5,5]
39+
console.log(PrimeFactors(104)); //Output : [2,2,2,13]

0 commit comments

Comments
 (0)