Skip to content

Commit ffa05d5

Browse files
committed
created a new way of solving highest common factor
1 parent 3de500e commit ffa05d5

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Maths/hfc1.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// numbers = [2, 4, 6]
2+
// numbers = [54, 24]
3+
numbers = [15, 25, 35]
4+
5+
function hcf(num, numbers) {
6+
7+
let commonFactors = [];
8+
let highestCommonFactor;
9+
10+
for (let i = 0; i < num; i++) {
11+
12+
for (let j = 1; j <= numbers[i]; j++) {
13+
14+
if (numbers[i] % j === 0) {
15+
16+
commonFactors.push(j)
17+
}
18+
19+
}
20+
21+
}
22+
23+
24+
let sortedCommonFactors = commonFactors.sort((a, b) => b - a);
25+
26+
27+
for (let k = sortedCommonFactors.length; k > 0; k--) {
28+
29+
if (sortedCommonFactors[k] == sortedCommonFactors[k + (num - 1)]) {
30+
31+
highestCommonFactor = sortedCommonFactors[k];
32+
33+
}
34+
}
35+
36+
return highestCommonFactor
37+
38+
}
39+
40+
41+
42+
43+
console.log(hcf(3, numbers))

0 commit comments

Comments
 (0)