02 Euclid's Algorithm for GCD

Eculid's Formla for GCD:

GCD(a,b)={bwhen a=0awhen b=0GCD(a%b,b)when a>bGCD(a,b%a)when b>a\text{GCD}(a, b) = \left\{ \begin{array}{ll} b & \text{when } a = 0 \\ a & \text{when } b = 0 \\ GCD(a \% b, b) & \text{when } a > b \\ GCD(a, b \% a) & \text{when } b > a \\ \end{array} \right.

Iterative Method

int GCD(int a, int b) {
  while((a % b) > 0) {
    int temp = a;
    a = b;
    b = temp % b;
  }
  return b;
}

Recursive Method

int gcd(int a, int b) 
{  
    
    // BASE CASE
    if (a == 0) 
       return b; 
    if (b == 0) 
       return a;   
    if (a == b) 
        return a; 
  
    // a is greater 
    if (a > b) 
        return gcd(a % b, b); 
    return gcd(a, b % a); 
}

Question 1

LeetCode: Find Greatest Common DIvisor of Array
Solution

Iterative Solution

Recursive Solution

Question 2

LeetCode: Greatest Common Divisor of Strings
Solution

Last updated