Extended Forms of Euclidean Algorithms

Source: Internet
Author: User

This algorithm is used to calculate the integers x and y that meet the following conditions:

D = gcd (a, B) = AX + by (D is the maximum approximate number of A and B)

 

Pseudocode provided in the introduction to algorithms:

Extended_euclid (A, B)

1 If B = 0

2 Return (A, 1, 0)

3 else (D1, X1, Y1) = extended_euclid (B, A mod B)

4 (D, x, y) = (D2, Y1, Y1-(A/B) * Y1)

5 return (D, x, y)

 

The fourth line is the key.

 

It does not matter if you cannot understand it. The derivation process is as follows:

  

Gcd (a, B) = gcd (B, A % B), both of which are in type 1, with AX + by = B * X1 + (a % B) * Y1.

Because I % J = I-(I/J) * J, the right side can be deformed as follows:

B * X1 + (a % B) * Y1 = B * X1 + (a-(A/B) * B) * Y1 = A * Y1 + B * (x1-(A/B) * Y1 ), the final result is AX + by = A * Y1 + B * (x1-(A/B) * Y1)

That is to say, the X of the previous depth is equal to the Y1 of the next depth, and the Y of the previous depth is equal to the x1-(A/B) * Y1 OF THE NEXT depth. Note that the Division used in the above derivation is integer division.

 

Example:

Question link: http://acm.nyist.net/JudgeOnline/problem.php? PID = 1, 775

Idea: Install Code directly to facilitate understanding.

  

# Include <iostream> # include <cstdio> using namespace STD; int X, Y, D; // D indicates the maximum public approx. Void extend_gcd (int A, int B) {int T; // records the current x value, because if (B = 0) {x = 1; y = 0; D = A;} is used to calculate y ;} else {extend_gcd (B, A % B); t = x; X = y; y = T-(A/B) * y ;}} int main () {int A, B; while (scanf ("% d", & A, & B )! = EOF) {extend_gcd (a, B); printf ("% d \ n", x, y);} return 0 ;}

 

References: http://www.cnblogs.com/ka200812/archive/2011/09/02/2164404.html

 

Extended Forms of Euclidean Algorithms

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.