Extended Euclidean algorithm

Source: Internet
Author: User
Tags greatest common divisor

For a, B is not all 0, there is an integer x and y make gcd (A, A, a) =x*a+y*b; Integer... That is, you can make it negative.

Code:

1 intEXGCD (intAintBint&x,int&y)2 {3   if(b==0)4   {5x=1;6y=0;7     returnA;8   }9   intR=EXGCD (b,a%b,x,y);Ten   intt=x; Onex=y; Ay=t-a/b*y; -   returnR; -}
extended Euclidean algorithm

  

First, let's take a look at how he was formed. Push up from the last layer: first b=0 get greatest common divisor a, return a; Now look at a layer, from the R that sentence to continue to run down, you can know, since then, every time from the R sentence to get the greatest common divisor, and then go down to execute ...

For a, b for the two layer, B is a, B greatest common divisor, then there is B = x1*a + y1*b; (i.e. x1=0; Y1=1;)

Similarly, for the three layer of a, B, two layers of B is also this layer a, B greatest common divisor have b ' = x2*a + y2*b; b ' =a%b;   B ' =x1*a ' +y1*b '; B ' =x1*b+y1* (A%B);

---> x1*b+y1* (a%b) = x2*a+ y2*b;

----> (* * *) This step is critical. is to dissolve a%b x1*b+y1* (a-a/b*b) = X2*a + y2*b (except in computer programming)

-----> Merge Similar Terms x1*b + A * y1-(a/b*b) *y1= x2*a+y2*b;

----> b* (x1-a/b*y1) +a*y1=x2*a+y2*b;

----->  x2=y1; y2=x1-a/b *y1; (La-la-la finally came out,,)

That is, the next layer of x is equal to the previous layer of Y, the next layer of Y is equal to the previous layer of the x-a/b* on the Y, here A/b is this layer of ... Although here is the Special column: Inverted three layer interpretation, but because there is no specific x, Y value, so the formula should be universal. This explains the reason of our code, at the same time, from the two layer to know x1=0; Y1=1;

The recursive way of writing first to the bottom, and then by the bottom of the X, y step up to get the top of x, Y, is we want to ask for X, y ...

......

Extended Euclidean algorithm

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.