Purpose: Alongside , find integers with (Bézout coefficients), in .

Algorithm

  1. Base case: , with , .
  2. Otherwise recurse on , obtaining with .
  3. Substitute :
  4. So and .

Code

// returns g = gcd(a,b) and sets x, y with a*x + b*y = g
long long extgcd(long long a, long long b, long long &x, long long &y) {
    if (b == 0) { x = 1; y = 0; return a; }
    long long x1, y1;
    long long g = extgcd(b, a % b, x1, y1);
    x = y1;
    y = x1 - (a / b) * y1;
    return g;
}
 
// modular inverse of a mod m (exists iff gcd(a,m) == 1)
long long modinv(long long a, long long m) {
    long long x, y;
    if (extgcd(a, m, x, y) != 1) return -1;   // no inverse
    return ((x % m) + m) % m;
}

An iterative version avoids recursion depth and is what you want inside tight loops:

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

Paradigm

Divide and conquer / recursion with back-substitution. The forward pass is the plain Euclidean algorithm; the extension is a linear back-substitution that carries the coefficients up the recursion.

Complexity

  • Time: — the same Fibonacci-worst-case bound as plain Euclid
  • Space: recursive, iterative

Proof of Correctness

By induction on the recursion depth. Base: . Step: assume the recursive call returns with . Substituting and regrouping (step 3 above) yields exactly , which is what the algorithm returns. ∎

Size bound: the returned coefficients satisfy and , so they never overflow if fit in the type.

Variants / Use Cases

  • Modular inverse when ; works for non-prime , unlike Fermat
  • Linear Diophantine equations is solvable iff ; scale the Bézout pair by
  • CRT for non-coprime moduli — merge congruences using the Bézout coefficients
  • Linear congruence
  • Continued fractions — the quotients are exactly the continued fraction expansion of
  • Garner’s algorithm — mixed-radix CRT reconstruction