题目链接:10104 - Euclid Problem
From Euclid it is known that for any positive integers A and B there exist such integers X and Y that AX + BY = D, where D is the greatest common divisor of A and B. The problem is to find for given A and B corresponding X, Y and D.
Input
The input will consist of a set of lines with the integer numbers A and B, separated with space (A, B < 1000000001).
Output
For each input line the output line should consist of three integers X, Y and D, separated with space. If there are several such X and Y , you should output that pair for which |X| + |Y | is the minimal. If there are several X and Y satisfying the minimal criteria, output the pair for which X ≤ Y .
Sample Input
4 6
17 17
Sample Output
-1 1 2
0 1 17
题意简述:
求出最大公约数gcd,并求解出使得: a*x + b*y = gcd 的通解 x 和 y。
(求通解x,y便是扩展欧几里得算法和欧几里得算法的区别所在)
题记:
此题为扩展欧几里得算法的裸题,记住这个套路,以后遇到直接用。
C++语言程序如下:
/* UVA10104 Euclid Problem */
#include <iostream>
using namespace std;
// 扩展欧几里得算法
int exgcd(int a, int b, int &x, int &y)
{
if (a % b == 0) {
x = 0;
y = 1;
return b;
}else {
int r, tx, ty;
r = exgcd(b, a % b, tx, ty);
x = ty;
y = tx - a / b * ty;
return r;
}
}
int main()
{
int a, b, r, x, y;
while(cin >> a >> b) {
r = exgcd(a, b, x, y);
cout << x << " " << y << " " << r << endl;
}
return 0;
}