# C++ Program to Implement Extended Euclidean Algorithm

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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

## Algorithm

Begin
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
End

## 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;
}

## Output

gcd 5