假设方程为ax+by=c; 其中a和b的最大公倍数为d
1.在利用exgcd计算a和b的最大公约数时,如果a==0&&b==0,d=0,如果a和b其中一个等于0,比如说:a=0,b=4,则d=4
2.exgcd正确计算的条件是a和b都不为负所以遇到a或b是负数的情况时,对负数取相反数,然后将求得的结果取相反数
3.要注意一些特殊情况:
(1)a=0,b=0时,只有c=0时,才能得到x=0,y=0的解
(2)a=0时,只有c%b==0时才能得到解
(3)b=0时,只有c%a==0时才能得到解
4.c%d!=0时,说明方程无解
一道例题:传送门:点击打开链接
There is an equation ax + by + c = 0. Given a,b,c,x1,x2,y1,y2 you must determine, how many integer roots of this equation are satisfy to the following conditions : x1<=x<=x2, y1<=y<=y2. Integer root of this equation is a pair of integer numbers (x,y).
Input
Input contains integer numbers a,b,c,x1,x2,y1,y2 delimited by spaces and line breaks. All numbers are not greater than 108 by absolute value.
Output
Write answer to the output.
Sample Input
1 1 -3 0 4 0 4
Sample Output
4
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<cmath>
using namespace std;
typedef long long ll;
ll exgcd(ll a, ll b, ll &x, ll &y)
{
if(b == 0)
{
x = 1;
y = 0;
return a;
}
ll d = exgcd(b, a % b, x, y);
ll tmp = x;
x = y;
y = tmp - a / b * y;
return d;
}
int main()
{
ll a, b, c, x1, x2, y1, y2;
while(~scanf("%lld%lld%lld%lld%lld%lld%lld", &a, &b, &c, &x1, &x2, &y1, &y2))
{
c = -c;
if(a == 0&& b == 0)
{
if(c != 0)
printf("0\n");
else printf("%lld\n", (x2-x1+1)*(y2-y1+1));
}
else if(a==0)
{
if(c%b==0)
{
if(y1>c/b||y2<c/b)
printf("0\n");
else printf("%lld\n",x2-x1+1);
}
}
else if(b==0)
{
if(c%a==0)
{
if(x1>c/a||x2<c/a)
printf("0\n");
else printf("%lld\n",y2-y1+1);
}
}
else
{
if(a < 0)
{
a = -a;
ll tmp = x1;
x1 = -x2;
x2 = -tmp;
}
if(b < 0)
{
b = -b;
ll tmp = y1;
y1 = -y2;
y2 = -tmp;
}
ll x, y;
ll d = exgcd(a, b, x, y);
if(c % d)
printf("0\n");
else
{
x = x*(c/d);
y = y*(c/d);
ll bd = b/d, ad = a/d;
ll ri1 = (ll)floor((double)(x2-x)/(double)bd);
ll ri2 = (ll)floor((double)(y-y1)/(double)ad);
ll li1 = (ll)ceil((double)(x1-x)/(double)bd);
ll li2 = (ll)ceil((double)(y-y2)/(double)ad);
ll ri = min(ri1, ri2);
ll li = max(li1, li2);
if(ri < li)
printf("0\n");
else printf("%lld\n", ri-li+1);
}
}
}
}