C Program for Extended Euclidean algorithms?

The Extended Euclidean Algorithm is used to find the greatest common divisor (GCD) of two integers along with the coefficients x and y such that −

ax + by = gcd(a, b)

This algorithm extends the standard Euclidean algorithm by not only computing the GCD but also finding the linear combination coefficients. It uses the recursive relation gcd(a, b) = gcd(b mod a, a) while keeping track of the coefficients.

Syntax

int extendedGCD(int a, int b, int* x, int* y);

Algorithm

ExtendedEuclidean(a, b, x, y)
begin
    if a is 0, then
        x := 0
        y := 1
        return b
    end if
    gcd := ExtendedEuclidean(b mod a, a, x1, y1)
    x := y1 - (b/a) * x1
    y := x1
    return gcd
end

Example

Here's a complete implementation of the Extended Euclidean Algorithm −

#include <stdio.h>

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

int main() {
    int a = 60, b = 25;
    int x, y;
    
    int gcd = extendedGCD(a, b, &x, &y);
    
    printf("GCD(%d, %d) = %d<br>", a, b, gcd);
    printf("Coefficients: x = %d, y = %d<br>", x, y);
    printf("Verification: %d*%d + %d*%d = %d<br>", a, x, b, y, a*x + b*y);
    
    return 0;
}
GCD(60, 25) = 5
Coefficients: x = -2, y = 5
Verification: 60*-2 + 25*5 = 5

Key Points

  • The algorithm finds both the GCD and the Bézout coefficients x and y
  • Time complexity is O(log min(a, b)), same as the standard Euclidean algorithm
  • The coefficients satisfy the equation ax + by = gcd(a, b)
  • This algorithm is useful in modular arithmetic and cryptography

Conclusion

The Extended Euclidean Algorithm efficiently computes both the GCD and the linear combination coefficients. It's particularly valuable in number theory applications and forms the basis for many cryptographic algorithms.

Updated on: 2026-03-15T11:03:05+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements