@ParasArora/

greatest common divisor (GCD or HCF)

Nodejs

No description

fork
loading
Files
  • index.js
index.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
40
// iterative method
function gcd(a, b){
  let num1 = Math.min(a, b);
  let num2 = Math.max(a, b);

  if(a == 0) return b;
  if(b == 0) return a;

  while(num2 % num1 !== 0){
    let temp = num1;
    let remainder = num2 % num1;
    num1 = remainder;
    num2 = temp;
  }

  return num1;
}

// recursive (1) - made by me
function gcdDispatcher(x, y){
  let num1 = Math.min(x, y);
  let num2 = Math.max(x, y);

  if(x == 0) return y;
  if(y == 0) return x;
  if(num2 % num1 == 0) return num1;

  return gcdDispatcher(num2 % num1, num1);
}

// recursive (2) - found on geeksForGeeks
function gcdRec(a, b){
  if(b == 0) return a;
  return gcdRec(b, a % b);
}

gcd(12, 0);
gcdDispatcher(12, 0);
gcdRec(18, 12);
gcdRec(-4, 6);
node v10.16.0