|
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 | | - * @returnsreturn 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 | | -constGetEuclidGCD=(arg1,arg2)=>{ |
15 | | -// firstly, check that input is a number or not. |
16 | | -if(typeofarg1!=='number'||typeofarg2!=='number'){ |
17 | | -returnnewTypeError('Argument is not a number.') |
| 7 | +exportfunctionGetEuclidGCD(a,b){ |
| 8 | +if(typeofa!=='number'||typeofb!=='number'){ |
| 9 | +thrownewTypeError('Arguments must be numbers') |
18 | 10 | } |
19 | | -// check that the input number is not a negative value. |
20 | | -if(arg1<1||arg2<1){ |
21 | | -returnnewTypeError('Argument is a negative number.') |
| 11 | +if(a===0&&b===0)returnundefined// infinitely many numbers divide 0 |
| 12 | +a=Math.abs(a) |
| 13 | +b=Math.abs(b) |
| 14 | +while(b!==0){ |
| 15 | +constrem=a%b |
| 16 | +a=b |
| 17 | +b=rem |
22 | 18 | } |
23 | | -// Find a minimum of both numbers. |
24 | | -letless=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 | +returna |
30 | 20 | } |
31 | | - |
32 | | -export{GetEuclidGCD} |
0 commit comments