C++ Program to Implement Extended Euclidean Algorithm

C++Server Side ProgrammingProgramming

The Extended Euclidean Algorithm is just a another way of calculating GCD of two numbers. It has extra variables to compute ax + by = gcd(a, b). It's more efficient to use in a computer program


   Declare variable a, b, x and y
   gcdExtended(int a, int b, int *x, int *y)
   if (a == 0)
      *x = 0;
      *y = 1;
   return b;
   Take two variables to store the result
   Update x and y using results of recursive call

Example Code

#include <bits/stdc++.h>
using namespace std;
int gcdExtended(int a, int b, int *x, int *y) {
   if (a == 0) {
      *x = 0;
      *y = 1;
      return b;
   int x1, y1;
   int gcd = gcdExtended(b%a, a, &x1, &y1);
   *x = y1 - (b/a) * x1;
   *y = x1;
   return gcd;
int main() {
   int x, y;
   int a = 35, b = 15;
   cout<<"gcd "<<gcdExtended(a, b, &x, &y);
   return 0;


gcd 5
Updated on 30-Jul-2019 22:30:25