forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindHcf.js
More file actions
31 lines (26 loc) · 738 Bytes
/
FindHcf.js
File metadata and controls
31 lines (26 loc) · 738 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
author: redfly1
More about HCF:
https://en.wikipedia.org/wiki/Greatest_common_divisor
*/
const findHCF = (x, y) => {
// If the input numbers are less than 1 return an error message.
if (x < 1 || y < 1) {
return 'Please enter values greater than zero.'
}
// If the input numbers are not integers return an error message.
if (x !== Math.round(x) || y !== Math.round(y)) {
return 'Please enter whole numbers.'
}
// Now apply Euclid's algorithm to the two numbers.
while (Math.max(x, y) % Math.min(x, y) !== 0) {
if (x > y) {
x %= y
} else {
y %= x
}
}
// When the while loop finishes the minimum of x and y is the HCF.
return Math.min(x, y)
}
export { findHCF }