Extended Euclidean Algorithm
Extended Euclidean Algorithm
GCD of two numbers is the largest number that divides both of them. A simple way to
● If we subtract smaller number from larger (we reduce larger number), GCD
doesn’t change. So if we keep subtracting repeatedly the larger of two, we
end up with GCD.
● Now instead of subtraction, if we divide smaller number, the algorithm stops
when we find remainder 0.
// Function to return
// gcd of a and b
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Driver Code
int main()
{
int a = 10, b = 15;
cout << "GCD(" << a << ", "
<< b << ") = " << gcd(a, b)
<< endl;
a = 35, b = 10;
cout << "GCD(" << a << ", "
<< b << ") = " << gcd(a, b)
<< endl;
a = 31, b = 2;
cout << "GCD(" << a << ", "
<< b << ") = " << gcd(a, b)
<< endl;
return 0;
}
Output :
GCD(10, 15) = 5
GCD(35, 10) = 5
GCD(31, 2) = 1
Extended Euclidean algorithm also finds integer coefficients x and y such that:
ax + by = gcd(a, b)
Examples:
Input: a = 30, b = 20
Output: gcd = 10
x = 1, y = -1
(Note that 30*1 + 20*(-1) = 10)
Input: a = 35, b = 15
Output: gcd = 5
x = 1, y = -2
(Note that 10*0 + 5*1 = 5)
The extended Euclidean algorithm updates results of gcd(a, b) using the results
calculated by recursive call gcd(b%a, a). Let values of x and y calculated by the
recursive call be x1 and y1. x and y are updated using below expressions.