There are two number a B, now we ask for a B greatest common divisor, how to ask? Enumerate their factors? Not realistic, when a B is very large, the enumeration looks so naïve, how to do?
Euclid has a very useful theorem: Gcd (A, b) = gcd (b, a%b) so that we can solve the greatest common divisor of a and B in almost log time complexity, which is the Euclidean algorithm, which is described in the C + + language as follows:
Because it is written in a recursive, it looks very concise, but also very good memory. So what is the extension of Euclid?
Now that we know that the greatest common divisor of A and B are gcd, then we will be able to find such x and Y, so that: A*x + b*y = GCD This is an indefinite equation (in fact, a loss graph equation), there are many solutions is certain, but as long as we find a special set of solutions x0 and y0 that , we can use x0 and y0 to express the general solution of the indefinite equation:
x = x0 + (B/GCD) *t
y = y0– (A/GCD) *t
t = 0,1,-1,2,-2 .....
Now, we know that there must be X and Y to make: a*x + b*y = gcd, so, how do you find this special solution x and y? Just add a few tweaks to the Euclidean algorithm.
We observed that the Euclidean algorithm stopped in the state: A= gcd, b = 0, so, can this give us a way to solve X y? Because, at this time, as long as a = GCD coefficient is 1, then as long as the coefficient of B is 0 or other value (no matter how much, anyway, any number multiplied by 0 equals 0 but a coefficient must be 1), then we will have: a*1 + b*0 = gcd
Of course this is the final state, but can we reverse from the final state to the original state?
Assuming that we are currently dealing with the greatest common divisor of A and B, and finding that X and y make a*x + b*y= GCD, we have already found the next state: A%b of B and greatest common divisor, and found a set of X1 and Y1 to make: B*x1 + (a%b) *y1 = GC D, is there a relationship between the two neighboring states?
We know: A%b = A-(A/b) *b (the "/" here refers to the division of integers, such as 5/2=2, 1/3=0), then we can get further:
GCD = B*x1 + (A-(A/b) *b) *y1
= b*x1 + a*y1– (A/b) *b*y1
= A*y1 + b* (x1–a/b*y1)
Compare our states before: Ask for a set of X and Y to make: a*x + b*y = gcd, do you find anything?
Over here:
x = y1
y = x1–a/b*y1
The above is the whole process of extending Euclid's algorithm, still using recursion to write:
int ex_gcd (int A,int b,int &x,int &y) { if (! b) { x=1, y=0; return A; } int ans=ex_gcd (b,a%b,x,y); int tmp=x; x=y,y=x-a/b*y; return
Simplified:
int ex_gcd (int A,int b,int &x,int &y) { if (! b) { x=1, y=0; return A; } int ans=ex_gcd (b,a%b,y,x); Y-=a/b*x; return ans;}
http://blog.csdn.net/zhjchengfeng5/article/details/7786595
Baidu Library
Extended Euclidean algorithm