扩展欧几里得算法
已知(a, b)求解(p, q), 使得p * a + q * b = GCD(a, b);
一定有解;
因为GCD(a, b) = GCD(b, a%b)
所以p * a + q * b = GCD(a, b)
= GCD(b, a%b)
= p * b + q * a % b
= p * b + q * (a - a/b * b)
= p * b + q * a - q * a/b * b
= q * a + (p - a/b * q) * b
就把a与b的线性组合转换为b,a%b的线性组合
不断缩小,当b=0时,p=1,q=1
递归求解
【code】ax+by=gcd(a,b) 求解x,y
#include <iostream>
using namespace std;
//Extended_GCD
int Extended_GCD(int a, int b, int &p, int &q) {
if(b == 0) {
p = 1;
q = 0;
return a;
}
int gcd = Extended_GCD(b, a%b, p, q), tmp;
tmp = p;
p = q;
q = tmp - a/b * q;
return gcd;
}
int main() {
int gcd, a, b, x, y;
cin >> a >> b;
gcd = Extended_GCD(a, b, x, y);
cout << gcd << ' ' << x << ' ' << y << endl;
return 0;
}