Extended Euclid EXGCD

Source: Internet
Author: User

• 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.