Extended Euclidean algorithm and its implementation

Source: Internet
Author: User
Tags gcd greatest common divisor


Euclidean algorithm, namely the greatest common divisor method, is used to find the integer a, b.

Euclidean algorithm C + + implementation code: (no need to determine a, b size relationship)

Long Long gcd (long long A,long long b) {return B?GCD (b,a%b): A;}



Extended Euclidean algorithm: Set A and B are not all 0, there is an integer x and y, making gcd (A, b) = xa + YB

Proof: Suppose A>b

When b==0: gcd (A, b) = A, at this time x=1, y=0

When ab!=0:

Set: x1a + y1b = gcd (A, B)

x2b + y2 (a%b) = gcd (b,a%b)

Because gcd (A, b) = = GCD (b,a%b)

So x1a + y1b = x2b + y2 (a%b) = x2b + y2 (a-a/b*b) =y2a + x2b-y2 (A/b) *b

So x1 = y2, y1 = x2-(A/b) y2

This can be based on x2, y2 to find out the solution of X1, y1.


Extended Euclid C + + implementation code 01:

Long Long exgcd (long long A,long long b,long long& x,long long& y) {    if (b==0) {        x=1;        y=0;        return A;    }    Long Long D=EXGCD (b,a%b,x,y);    Long long tmp=x;    x=y;    Y=tmp-a/b*y;    return D;}

Extended Euclid C + + implementation code 02:

#define LL Long longvoid exgcd (ll a,ll b,ll& d,ll& x,ll& y) {    if (!b) {D=a;x=1;y=0;return;}    EXGCD (b,a%b,d,y,x);    Y-= a/b*x;    return;}

Extended Euclidean algorithm and its implementation

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.