回复:(leeco)求解三元一次不定方程
The Chinese remainder theorem is the key to solve
a_1 x_1 + a_2 x_2 + ... + a_r x_r = n
for integer solutions. You may want to be familiar with the theorem.
For the case r=2, i.e., a_1 x_1 + a_2 x_2 = n, the extended Euclid algorithm is your friend. I implemented it inside the code below.
For the case r=3, by using the extended Euclid algorithm twice, you arrive at the solution.
For the case r>3, you can still use the algorithm r-1 times to solve it. But it become so cubersome that you want to use the Chinese remainder theorem and its corresponding algorithm instead.
I am not using the theorem in the code.
=================================================
#include <iostream>
using namespace std;
int gcd(int a, int b, int& x, int& y)
{
int x2=1, y2=0, t, q, a2=a, b2=b;
x=0;
y=1;
while(b)
{
t = b;
q = a / b;
b = a% b;
a = t;
t = x;
x = x2-q*x;
x2 = t;
t = y;
y = y2-q*y;
y2 = t;
}
x=x2;
y=y2;
// make x>=0, y<=0
x=x+b2/a;
y=y-a2/a;
return a;
}
int main()
{
int a, b, c, x, y, z, n, v, w, x1, y1, x2, y2, t;
while(cin>>x>>y>>z>>n)
{
v=gcd(x, y, x1, y1);
w=gcd(v, z, x2, y2);
if(n%w)
cout<<-1<<endl;
else
{
t=n/w;
// calculate one solution: here a>=0, b<=0, c>=0
a=t*x2*x1;
b=t*x2*y1;
c=t*y2;
// adjust b and c to make b non-negative
c=-c;
t=-b/z+1;
b+=z*t;
c+=t*y;
cout<<a<<" "<<b<<" "<<c<<endl;
}
}
return 0;
}