C Program for Extended Euclidean algorithms?

CServer Side ProgrammingProgramming

Here we will see the extended Euclidean algorithm implemented using C. The extended Euclidean algorithm is also used to get the GCD. This finds integer coefficients of x and y like below −

𝑎𝑥+𝑏𝑦 = gcd(𝑎,𝑏)

Here in this algorithm it updates the value of gcd(a, b) using the recursive call like this − gcd(b mod a, a). Let us see the algorithm to get the idea


EuclideanExtended(a, b, x, y)

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


 Live Demo

#include <stdio.h>
int EuclideanExtended(int a, int b, int* x, int* y) {
   if (a == 0) {
      *x = 0;
      *y = 1;
      return b;
   int xtemp, ytemp; // To store results of recursive call
   int res = EuclideanExtended(b % a, a, &xtemp, &ytemp);
   *x = ytemp - (b / a) * xtemp;
   *y = xtemp;
   return res;
int main() {
   int x, y;
   int a = 60, b = 25;
   int res = EuclideanExtended(a, b, &x, &y);
   printf("gcd(%d, %d) = %d", a, b, res);


gcd(60, 25) = 5
Published on 26-Jul-2019 12:28:54