<span style="font-family: Simsun; font-size: 12px; background-color: rgb(255, 255, 255);">The Problem</span>
<span style="font-family: Simsun; font-size: 12px; background-color: rgb(255, 255, 255);">The Problem</span>
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.
The Input
The input will consist of a set of lines with the integer numbers A and B, separated with space (A,B<1000000001).
The 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 (primarily) and X<=Y (secondarily).
Sample Input
4 6 17 17
Sample Output
-1 1 2 0 1 17
扩展欧几里得模板题
当b=0时 返回a 为最大公约数 以及 x=1 y=0 的解使得 a = x*a + b*y 否则扩展gcd 首先算出 d = b*x'+ (a mod b)*y'=a*x+b*y d = b*x'+ (a-b*a/b)y' = a*y' + b*(x'-a/b*y')
y’ = x
x' - a/b*y' = y
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <string> #include <algorithm> #include <queue> using namespace std; int a,b; int d,x,y; void extended_euclid(int a,int b){ if(b==0){ d = a; x = 1; y = 0; return; }else{ extended_euclid(b,a%b); int t = y; y = x - a/b*y; x = t; //cout<<x<<" "<<y<<endl; return; } } int main(){ while(cin >> a >> b){ extended_euclid(a,b); cout<<x<<" "<<y<<" "<<d<<endl; } return 0; }