Extended Euclidean Algorithm (EEA)

The extended Euclidean Algorithm allows us to calculate , and solve the Linear Diophantine Equation for in terms of and , where

We know that an answer always exists from Bezout’s Lemma.

LCM and GCD

int gcd(int a, int b) { // Euclidean Algorithm, however this is already implemented in C++
    if (b == 0) return a;
    return gcd(b, a % b);
}
 
int lcm (int a, int b) {
    return a / gcd(a, b) * b;
}

Recursive

int gcd(int a, int b, int& x, int& y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    int x1, y1;
    int d = gcd(b, a % b, x1, y1);
    x = y1;
    y = x1 - y1 * (a / b);
    return d;
}
 

Iterative (i think the way we learned in class)??

int gcd(int a, int b, int& x, int& y) {
    x = 1, y = 0;
    int x1 = 0, y1 = 1, a1 = a, b1 = b;
    while (b1) {
        int q = a1 / b1;
        tie(x, x1) = make_tuple(x1, x - q * x1);
        tie(y, y1) = make_tuple(y1, y - q * y1);
        tie(a1, b1) = make_tuple(b1, a1 - q * b1);
    }
    return a1;
}
 

There is something very important to observe about the table. If we are computing , then for each row of the table we have

Input: Integers , with Initialize: Construct the table with four columns so that

  • the columns are labeled ,
  • the first row in the table is ,
  • the second row in the table is .

Repeat: For ,

Stop: When Output: Set . Then , and and are a certificate of correctness.