Skip to content

Commit d914bd9

Browse files
added hcf finding algorithm (#104)
* added hcf finding algorith * Update and rename find_hcf.js to FindHcf.js Co-authored-by: vinayak <[email protected]>
1 parent ed4b295 commit d914bd9

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

maths/FindHcf.js

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
author: redfly1
3+
More about HCF:
4+
https://en.wikipedia.org/wiki/Greatest_common_divisor
5+
*/
6+
7+
function findHCF (x, y) {
8+
// If the input numbers are less than 1 return an error message.
9+
if (x < 1 || y < 1) {
10+
return 'Please enter values greater than zero.'
11+
}
12+
13+
// If the input numbers are not integers return an error message.
14+
if (x !== Math.round(x) || y !== Math.round(y)) {
15+
return 'Please enter whole numbers.'
16+
}
17+
18+
// Now apply Euclid's algorithm to the two numbers.
19+
while (Math.max(x, y) % Math.min(x, y) !== 0) {
20+
if (x > y) {
21+
x %= y
22+
} else {
23+
y %= x
24+
}
25+
}
26+
27+
// When the while loop finishes the minimum of x and y is the HCF.
28+
return Math.min(x, y)
29+
}
30+
console.log(findHCF(27, 36))

0 commit comments

Comments
 (0)