forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GetEuclidGCD.js
39 lines (37 loc) · 918 Bytes
/
GetEuclidGCD.js
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
32
33
34
35
36
37
38
39
function CheckInput(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new TypeError('Arguments must be numbers')
}
}
/**
* GetEuclidGCD Euclidean algorithm to determine the GCD of two numbers
* @param {Number} a integer (may be negative)
* @param {Number} b integer (may be negative)
* @returns {Number} Greatest Common Divisor gcd(a, b)
*/
export function GetEuclidGCD(a, b) {
CheckInput(a, b)
a = Math.abs(a)
b = Math.abs(b)
while (b !== 0) {
const rem = a % b
a = b
b = rem
}
return a
}
/**
* Recursive version of GetEuclidGCD
* @param {Number} a integer (may be negative)
* @param {Number} b integer (may be negative)
* @returns {Number} Greatest Common Divisor gcd(a, b)
*/
export function GetEuclidGCDRecursive(a, b) {
CheckInput(a, b)
a = Math.abs(a)
b = Math.abs(b)
if (b == 0) {
return a
}
return GetEuclidGCDRecursive(b, a % b)
}