Open In App

C Program for Extended Euclidean algorithms

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common factors. GCD 

C
// C program to demonstrate working of extended
// Euclidean Algorithm
#include <stdio.h>

// C function for extended Euclidean Algorithm
int gcdExtended(int a, int b, int* x, int* y)
{
    // Base Case
    if (a == 0) {
        *x = 0;
        *y = 1;
        return b;
    }

    int x1, y1; // To store results of recursive call
    int gcd = gcdExtended(b % a, a, &x1, &y1);

    // Update x and y using results of recursive
    // call
    *x = y1 - (b / a) * x1;
    *y = x1;

    return gcd;
}

// Driver Program
int main()
{
    int x, y;
    int a = 35, b = 15;
    int g = gcdExtended(a, b, &x, &y);
    printf("gcd(%d, %d) = %d", a, b, g);
    return 0;
}
Output:
gcd(35, 15) = 5

Time Complexity: O(Log min(a, b))

Auxiliary Space:  O(1)

Please refer complete article on Basic and Extended Euclidean algorithms for more details!


Article Tags :

Explore