(Extended Euclidean Algorithm)

Source: Internet
Author: User

Today, I roughly learned the Extended Euclidean algorithm.

Set A, B, and C as any integer, and G = gcd (A, B). The solution of the equation AX + by = G is (x1, Y1 ), when C is a multiple of G, a group of solutions for AX + by = C is (x1 * C/g, Y1 * C/G ); if C is not a multiple of G, there is no integer solution.

Ultraviolet A 10104:

He Problem

From Euclid it is known that for any positive integersAAndBThere exist such IntegersXAndYThatAx + by = d, WhereDIs the greatest common divisorAAndB.
The problem is to find for givenAAndBCorrespondingX,YAndD.

The input

The input will consist of a set of lines with the integer numbersAAndB, Separated with space (A, B <1000000001).

The output

For each input line the output line shoshould consist of three IntegersX, YAndD,Separated with space. If there are several suchXAndY, You shoshould output that pair for which| X | + | Y |Is
The minimal (primarily) andX <= y(Secondarily ).

Sample Input

4 617 17

Sample output

-1 1 20 1 17


Code:

# Include <cstdio>
Void gcd (int A, int B, Int & D, Int & X, Int & Y)
{
If (B = 0)
{
D =;
X = 1; y = 0;
}
Else
{
Gcd (B, A % B, D, Y, X );
Y-= x * (A/B );
}
}
Using namespace STD;
Int main ()
{

Int A, B, D, X, Y;
While (scanf ("% d", & A, & B )! = EOF)
{
Gcd (A, B, D, x, y );
Printf ("% d \ n", X, Y, d );
}
Return 0;
}

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.