Extended Euclid Algorithm:



This is the extended form of Euclid’s Algorithm explained in previous post. GCD(A,B) has a special property that it can always be represented in the form of an equation, i.e., Ax + By = GCD(A, B).

This algorithm gives us the coefficients (x and y) of this equation which will be later useful in finding the Modular Multiplicative Inverse. These coefficients can be zero or negative in their value. This algorithm takes two inputs as A and B and returns GCD(A, B) and coefficients of the  equations as output.


Implementation:


#include < iostream > int d, x, y; void extendedEuclid(int A, int B)
{ if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); int temp = x; x = y; y = temp - (A/B)*y; } } int main( )
{ extendedEuclid(16, 10); cout << ”The GCD of 16 and 10 is ” << d << endl; cout << ”Coefficient x and y are: ”<< x << “and “ << y << endl; return 0; }


Output:

The GCD of 16 and 10 is 2
Coefficient x and y are: 2 and -3


Initially, Extended Euclid Algorithm will run as Euclid Algorithm until we get GCD(A, B) or until B gets 0 and then it will assign x = 1 and y = 0. As B = 0 and GCD(A, B) is A in the current condition, so equation Ax + By = GCD(A, B) will be changed to A * 1 + 0 * 0 = A.

So the values of d, x, y in the whole process of extendedEuclid( ) function are:

1) d=2, x = 1, y = 0.
2) d=2, x = 0 , y = 1 - (4/2) * 0 = 1.
3) d=2, x = 1 , y = 0 - (6/4) * 1 = -1.
4) d=2, x = -1 , y = 1 - (10/6) * -1 = 2.
5) d=2 , x= 2, y = -1 - (16/10) * 2 = -3.

Time Complexity: The time complexity of Extended Euclid’s Algorithm is O(log(max(A, B))).






Comments

Popular posts from this blog

Fibonacci numbers with help of DP