Extended Euclid Algorithm Recursive Solution
Extended Euclid Algorithm in C++ (Recursive Solution) with Step-by-Step Explanations:
#include <iostream>
using namespace std;
int extendedGCD(int a, int b, int &x, int &y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
int x1, y1;
int gcd = extendedGCD(b, a % b, x1, y1);
x = y1;
y = x1 - (a / b) * y1;
return gcd;
}
int main() {
int a = 30, b = 20;
int x, y;
int gcd = extendedGCD(a, b, x, y);
cout << "GCD: " << gcd << ", x: " << x << ", y: " << y << endl;
return 0;
}
Include the necessary header files.
Define a function
extendedGCD
that takes two integersa
andb
as input, along with references tox
andy
.In the
extendedGCD
function, check ifb
is 0. If true, setx
to 1,y
to 0, and returna
.If
b
is not 0, declare variablesx1
andy1
.Call the
extendedGCD
function recursively with parametersb
,a % b
,x1
, andy1
, and store the result ingcd
.Update
x
with the value ofy1
, and updatey
with the expressionx1 - (a / b) * y1
.Return the value of
gcd
.In the
main
function, define integersa
andb
.Declare variables
x
andy
.Call the
extendedGCD
function with parametersa
,b
,x
, andy
, and store the result ingcd
.Output the values of
gcd
,x
, andy
to the console.Return 0 to indicate successful completion of the program.