• The extended Euclidean algorithm is used to solve a set of X, Y, in known a, b to satisfy the Bézout equation: ax+by = gcd (A, b) = d (The solution must exist, according to the correlation theorem in number theory). Extended Euclidean is commonly used in solving linear equations and equations. • Set A>b. • 1, apparently when B=0,GCD (A, b) =a. At this time x=1,y=0; 2,ab<>0 • Set AX1+BY1=GCD (A, A, b), bx2+ (a mod) y2=gcd (b,a mod b); • GCD (A, A, b) =gcd according to the naïve Euclidean principle (B,a mod B.); •: ax1+by1=bx2+ (a mod b) y2; namely: ax1+by1=bx2+ (a-[a/b]*b) y2=ay2+bx2-[a/b]*by2; is ax1+by1==ay2+b (x2-[a/b]*y2); According to the identity theorem: x1=y2; y1=x2-[a/b]*y2; So we get the solution to the x1,y1: the value of X1,y1 is based on the idea of x2,y2. is recursive definition, because GCD constant recursive solution will have a time b=0, so recursion can end. Code:
int exgcd (int A,int b,int& x,int&y) { if (b==0) { x=1; y=0; return A; } int x2,y2; int d=exgcd (b,a%b,x2,y2); x=y2; Y=x2-(A/b) *y2; return D;}
Extended Euclid EXGCD