Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Extended Euclid's GCD #319

Merged
merged 1 commit into from
Oct 4, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions C++/Algorithms/RecursionAlgorithms/ExtendedEuclid'sGCD.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*Extended Euclid's GCD

An algorithm to compute integers x and y such that
ax + by = gcd(a,b) for given a and b.
*/

#include <iostream>
using namespace std;
int gcd(int a, int b, int &x, int &y)
{
if (a == 0)
{
x = 0;
y = 1;
return b;
}
int x1, y1;
int d = gcd(b % a, a, x1, y1);
x = y1 - (b / a) * x1;
y = x1;
return d;
}

int main()
{
int x = 0, y = 0, a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "GCD of " << a << " and " << b << ": ";
cout << gcd(a, b, x, y);
return 0;
}