利用欧几里得除法计算出最大公约数
再反推出x和y的特解
求 ax+by=c 的**整数**解
#include <iostream>
using namespace std;
void gcd(int a, int b, int &x, int &y, int &g)
{
int x1 = 1, y1 = 0;
int x0 = 0, y0 = 1;
int r,q;
while(1)
{
q = a / b;
r = a - b * q;
x = x1 - x0 * q;
y = y1 - y0 * q;
if (b % r == 0)
break;
a = b, b = r;
x1 = x0, x0 = x;
y1 = y0, y0 = y;
}
g = r;
}
int main()
{
int x,y,g;
int a , b, c;
cin>>a>>b>>c;
if (a < b) //提高程序健壮性
{
int i = a;
a = b;
b = i;
}
gcd(a,b,x,y,g); //这一步求出来的x和y 为ax+by=(a,b)的整数解
if (c % g != 0) //因为若方程ax+by=c有整数解 (a,b)|c
{
cout<<"无整数解"<<endl;
return 0;
}
x = x*c/g; //这一步求的是ax+by=c 特解
y = y*c/g;
cout<<"x = "<<x<<" + "<<b/g<<" * t"<<endl; //通解
cout<<"y = "<<y<<" - "<<a/g<<" * t"<<endl;
cout<<"t ∈ Z"<<endl;
return 0;
}