Extended Euclidean algorithm, Euclidean Algorithm

Source: Internet
Author: User

Extended Euclidean algorithm, Euclidean Algorithm

Proof:

In mathematical language, this problem is solved by finding integers x and y so that ax + by = 1. It is not hard to find that if gcd (a, B )! = 1, there must be no solution. On the contrary, if gcd (a, B) = 1, there must be an integer pair (x, y) Meeting ax + by = gcd (, b) You can use the Extended Euclidean algorithm to solve the problem.

 

Assume that we have obtained the Integer Solutions of B * xt + (a % B) yt = gcd (B, a % B) for xt, yt

According to Euclidean algorithm, gcd (B, a % B) = gcd (a, B)

 

Listen B * xt + (a % B) * yt = gcd (a, B) ①

 

Again, a % B = a-(a/B) * B ② Note: Because in C ++, the numbers of two int types are directly divided without special processing, the result is that the quotient of two numbers is rounded down to an integer.

 

∴ ② Into ① To simplify it: 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 ;}

 

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.