Extended Euclidean algorithm, Euclidean Algorithm

Source: Internet
Author: User

Extended Euclidean algorithm, Euclidean Algorithm

2016.1.25

(Not updated)

1. Euclidean Algorithm (moving phase Division)

1. Purpose: quickly calculate the maximum number of common approx.

2. essence: gcd (a, B) = gcd (B, a % B)

3. Proof: If r = a mod B is set, we need to prove that gcd (a, B) = gcd (B, r)

If gcd (a, B) is set to c, a = mc, B = nc, and m, n are mutually qualitative. So r = a-kb = (m-kn) c, so c is also the factor of r.

If gcd (B, r)> c is set to d, B = m1 * d, r = n1 * d, so a = (m1 + n1) * d, then d is the factor of a, so gcd (a, B) = d, which is inconsistent with the question.

Therefore, gcd (a, B) = gcd (B, r)

4. Time Complexity: Obviously, after two recursion, the first parameter is reduced by at least half.

Therefore, the time complexity is roughly O (log max (a, B ))

5. Typical Example: Number of vertices on a line segment

 

Ii. Extended Euclidean Algorithm:

1. Purpose: quickly calculate the integer x and y so that ax + by = gcd (a, B)

2. essence code:

void extgcd(int a,int b,int &x,int &y){    if(!b)    {        x=1;y=0;        return a;    }    else    {        extgcd(b,a%b,y,x);        y-=(a/b)*x;     }}

 

3. Proof: Since gcd (a, B) = gcd (B, a % B)

So B * x1 + (a % B) * y1 = gcd (a, B)

A % B = a-(a/B) * B

Therefore, gcd (a, B) = B * x1 + (a-(a/B) * y1

= B * x1 + a * y1-(a/B) * B * y1

= A * y1 + B * (x1-a/B * y1)

For the x, y we want to make ax + by = gcd (a, B)

X = y1

Y = x1-a/B * y1

Certificate completion

As for the termination condition, when the Euclidean Algorithm terminates, a = gcd, B = 0, then when x = 1, y = 0, the target formula is required.

In addition, for the mandatory and sufficient condition of ax + by = c, why is c = gcd (a, B), you can Baidu's Yi Shu theorem.

4. Time Complexity: Consistent with euclidean Algorithm

5. Typical Example: Double Six

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.