|
1 | | -/* |
2 | | - Problem statement and Explanation : https://en.wikipedia.org/wiki/Euclidean_algorithm |
3 | | -
|
4 | | - In this method, we have followed the iterative approach to first |
5 | | - find a minimum of both numbers and go to the next step. |
6 | | -*/ |
7 | | - |
8 | 1 | /** |
9 | | - * GetEuclidGCD return the gcd of two numbers using Euclidean algorithm. |
10 | | - * @param {Number} arg1 first argument for gcd |
11 | | - * @param {Number} arg2 second argument for gcd |
12 | | - * @returns return a `gcd` value of both number. |
| 2 | + * GetEuclidGCD Euclidean algorithm to determine the GCD of two numbers |
| 3 | + * @param {Number} a integer (may be negative) |
| 4 | + * @param {Number} b integer (may be negative) |
| 5 | + * @returns {Number} Greatest Common Divisor gcd(a, b) |
13 | 6 | */ |
14 | | -const GetEuclidGCD = (arg1, arg2) => { |
15 | | - // firstly, check that input is a number or not. |
16 | | - if (typeof arg1 !== 'number' || typeof arg2 !== 'number') { |
17 | | - return new TypeError('Argument is not a number.') |
| 7 | +export function GetEuclidGCD (a, b) { |
| 8 | + if (typeof a !== 'number' || typeof b !== 'number') { |
| 9 | + throw new TypeError('Arguments must be numbers') |
18 | 10 | } |
19 | | - // check that the input number is not a negative value. |
20 | | - if (arg1 < 1 || arg2 < 1) { |
21 | | - return new TypeError('Argument is a negative number.') |
| 11 | + if (a === 0 && b === 0) return undefined // infinitely many numbers divide 0 |
| 12 | + a = Math.abs(a) |
| 13 | + b = Math.abs(b) |
| 14 | + while (b !== 0) { |
| 15 | + const rem = a % b |
| 16 | + a = b |
| 17 | + b = rem |
22 | 18 | } |
23 | | - // Find a minimum of both numbers. |
24 | | - let less = arg1 > arg2 ? arg2 : arg1 |
25 | | - // Iterate the number and find the gcd of the number using the above explanation. |
26 | | - for (less; less >= 2; less--) { |
27 | | - if ((arg1 % less === 0) && (arg2 % less === 0)) return (less) |
28 | | - } |
29 | | - return (less) |
| 19 | + return a |
30 | 20 | } |
31 | | - |
32 | | -export { GetEuclidGCD } |
0 commit comments