GCD

Proof: GCD of two numbers

/* Euclidean Algorithm implemented in C */
int gcd(int a, int b){
  if(b == 0){
    return a;
  }
  else{
    return gcd(b, a%b);
  }
}

Euclidean Algorithm to find gcd of two positive integers simply states that:

The above matrix shows the , where .

Number of Divisions Required

int gcd_divisions(int a, int b){
  if(b == 0){
    return 0;
  }
  else if(a >= b){
    return 1 + gcd_divisions(b, a%b);
  }
  else{
    return 1 + gcd_divisions(b, a);
  }
}

Let D(a, b) be the number of divisions required to find gcd(a, b) by euclidean algorithm, and define \(D(a, 0) = 0, \text{if b = 0}\) (i.e. No division required). Then the function D(a, b) is given by the recurrence relation:

The above matrix shows the number of divisions required to compute , where

Extended Euclidean Algorithm

typedef struct{
  int gcd;
  int x;
  int y;
} Triplet;

Triplet* new_triplet(){
  return (Triplet *)malloc(sizeof(Triplet));
}

Triplet* extEuclid(int a, int b){
  if(b == 0){
    Triplet* t = new_triplet();
    t->gcd = a;
    t->x = 1;
    t->y = 0;
    return t;
  }
  else{
    Triplet* t1 = extEuclid(b, a%b);
    Triplet* t = new_triplet();
    t->gcd = t1->gcd;

    /*
       x = y1 and y = x1 - (a/b)*y1
       See below for explanation.
    */
    t->x = t1->y;
    t->y = t1->x - (a/b) * t1->y;
    return t;
  }
}

Bézout’s identity - Let a and b be integers with gcd d. Then, there exist integers x and y such that .

Example

Many solution exists for the Bézout’s identity. We can find a solution by using Extended Euclidean Algorithm.

Formation

Let a and b be positive integers, then there exist integers x and y such that: \[ax+by=gcd(a, b)\tag{1}\] Also, \[bx_1 + (a \bmod b)y_1 = gcd(b, a \bmod b)\] By using, , \[bx_1 + (a \bmod b)y_1 = gcd(a, b)\] We know that \[bx_1 + (a - b \lfloor \frac{a}{b} \rfloor)y_1 = gcd(a, b)\] By using eqation (1) \[b(x_1 - \lfloor \frac{a}{b} \rfloor y_1) + ay_1 = ax + by\] By this equation we get, \[x=y_1\] \[y=x_1 - \lfloor \frac{a}{b} \rfloor y_1\] which forms are two equation to form Extended Euclidean Algorithm.

When b = 0,
\[ax + by = gcd(a, b)\] \[\implies ax = gcd(a, 0)\] \[\implies x = 1, y = 0\] which forms our base case in the algorithm above.