#include <iostream>
using namespace std;
int Euclidean(int n,int m,int &x,int &y)
{
if(m ==0 )
{
x = 1;
y = 0;
return n;
}
int g = Euclidean(m, n%m, x, y );
int t = x - (n / m )*y;
x = y;
y = t;
return g;
}
int normalEuclidean(int n,int m)
{
if( m ==0)
return n;
else if (n % m ==0 )
return m;
else return (m,n%m);
}
int main()
{
int a,b,c;
while(cin>>a>>b>>c)
{
int d = normalEuclidean(a, b) ;
if(c %d ==0)
{
int tempa = a/d;
int tempb = b/d;
int tempc = c/d;
int s,t;
int gcd = Euclidean(tempa,tempb,s,t);
cout<<gcd <<" is 1 ?"<<endl;
cout<<"special solu x is "<<(c/d)*s <<" pecial solu y is "<<(c/d)*t<<endl;
cout<<" universal solu x is "<< (c/d)*s <<" + k* "<<b/d<< " and universal solu y is "<<(c/d)*t <<" -k* "<<a/d<<endl;
}
}
system("pause");
return 0;
}
上面的代码求得是丢番方程的求解,一个是特殊解,一个是通解,否则ax + by = c 就没有解了。因为这是两个变量的方程,所以不是没有就是无数。可以对变量的范围进行限制。
Euclidean(tempa,tempb,s,t);这个函数是拓展的欧几里得算法。
下面是其中的一个实现。
#include <iostream>
using namespace std;
int Euclidean(int n,int m,int &x,int &y)
{
if(m ==0 )
{
x = 1;
y = 0;
return n;
}
int g = Euclidean(m, n%m, x, y );
int t = x - (n / m )*y;
x = y;
y = t;
return g;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
int x,y;
if(Euclidean(n,m,x,y))
{
cout<<x<<" is x "<<y<<" is y "<<Euclidean(n,m,x,y)<<" is gcd"<<endl;
cout<< x * n + y * m <<" == "<< Euclidean(n,m,x,y)<<endl;
}
}
system("pause");
return 0;
}