转载请注明出处,谢谢合作。
http://blog.csdn.net/fanhansheng/article/details/52743669
对于形如”Ax+By=C”的式子,求二元一次不等式的一组特解。令m = gcd(a, b);
其存在解的条件为C为A和B最大公约数的整数倍。
推导:
bx + (a%b)y = gcd(b, a%b); —–1
ax+by = gcd(a, b); —– 2
由于a%b = a - a/b*b;
bx + (a - a / b * b)y = gcd(b, a%b) ; ——3
从一式得二式的推导过程为
根据等效定理: 1式 <=>3式
ax =ay;
bx - y * a/b*b = by;
y = x - a/b*y;
#include “iostream”
#include “string”
#include “cstdio”
#include “algorithm”
using namespace std;
long long x , y;
long long exgcd(long long a, long long b)
{
long long t, r;
if(b==0)
{
x=1;
y=0;
return a;
}
r = exgcd(b, a%b);
t = x;
x = y;
y = t - a/b*y;
return r;
}
void solve(long long a,long long b ,long long m) // 求方程ax + by = m 最小正整数x的解,否则无解
{
long long gcd = exgcd(a,b);
if(m%gcd!=0)
return ; //此时原方程无解
long long r = b / gcd;
x = (x % r + r) % r;
y = (gcd - a * x) / b;//相应x的y值
}
int main()
{
long long a, b, m;
while(~scanf("%lld %lld %lld", &a, &b, &m))
{
solve(a, b, m);
printf("%lld %lld\n", x, y);
}
return 0;
}