64,636
社区成员
发帖
与我相关
我的任务
分享
/**
*judge if linear equations has positive integer solutions
*vs 2012
*c++11
*/
#include <iostream>
using namespace std;
int main()
{
//TODO :以下未考虑除数为0
double a=0,b=0,c=0;
cout<<"Enter a,b,c:"<<endl;
cin>>a>>b>>c;
bool swapped=a>b;
if(swapped)swap(a,b);
double u,v;
u=c/a;
v=b/a;
double uf=u-static_cast<int>(u);
double vf=v-static_cast<int>(v);
const double epsilon=(numeric_limits<double>::epsilon());
int upb=static_cast<int>(c/b);
int less=-1;
for (int i = 1; i <= upb; i++)
{
double x=u-v*i;
double xx=floor(x+.5);
if(fabs(x-xx)<=epsilon)
{
if(swapped)
cout<<"A sultion : "<<i<<" , "<<static_cast<int>(x)<<endl;
else
cout<<"A sultion : "<<static_cast<int>(x)<<" , "<<i<<endl;
break;
}
}
system("pause");
}
有点退化的味道
#include<iostream>
#include <cstring>
typedef long long lint;
lint ex_gcd(lint a, lint b, lint& x, lint& y)
{
if(b == 0)
{
x = 1;
y = 0;
return a;
}
lint r = ex_gcd(b, a % b, x, y);
lint t = x;
x = y;
y = t - a / b * y;
return r;
}
bool check(lint a, lint b, lint c, lint& x, lint& y)
{
lint r = ex_gcd(a, b, x, y);
if(c % r)
{
return false;
}
a /= r; b /= r; c /= r;
x *= c;
x = ((x % b) + b ) % b;
y = (c - a * x) / b;
return y >= 0;
}
int main()
{
lint a = 3000000000000L;
lint b = 5000000000000L;
lint c = 8000000000000L;
lint x, y;
if(check(a, b, c, x, y))
{
printf("其中一组解是:\n x = %lld, y = %lld\n", x, y);
}
else
{
printf("无解\n");
}
return 0;
}