Extended Euclidean algorithm

Source: Internet
Author: User
Tags gcd

Prove:

The problem with mathematical language is that the integer x, y makes ax+by=1. It is not difficult to find, if GCD (A, B)!=1 must have no solution, on the contrary, if gcd (A, B) =1 that there must be an integer pair (x, y) satisfies the AX+BY=GCD (A, B), you can use the extended Euclidean algorithm to solve the answer

Suppose we have obtained b*xt+ (a%b) yt=gcd (b,a%b) integer solution XT, YT

The Euclidean algorithm shows that gcd (b,a%b) =GCD (A, B)

∴b*xt+ (a%b) *YT=GCD (A, b) ①

∵a%b=a-(A/b) *b② Note: because in C + +, the number of two int types is not directly divided by special processing, the result is a value of two number of quotient down rounding

∴ ② into ①: a*yt+b* (xt-(A/b) *yt) =GCD (A, B)

The code is as follows:

int extgcd (int A,int b,int &x,int &y) {int d= A; if (b!=0) {    D=extgcd (b,a%b,y,x);    Y-= (A/b) *x;} Else {x=1; y=0;} return D;}

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.