BZOJ5027: 数学题 数论

Description
给出a,b,c,x1,x2,y1,y2,求满足ax+by+c=0,且x∈[x1,x2],y∈[y1,y2]的整数解有多少对?


Sample Input
1 1 -3 0 4 0 4


Sample Output
4


求一下第一个范围的x的范围,
再求一下第二个范围的x的范围。
求交集即可。
有特判,如:a=0,b=0


#include 
#include 
#include 

using namespace std;
typedef long long LL;
LL _max(LL x, LL y) {return x > y ? x : y;}
LL _min(LL x, LL y) {return x < y ? x : y;}

LL exgcd(LL a, LL b, LL &x, LL &y) {
	if(b == 0) {x = 1; y = 0; return a;}
	else {
		LL tx, ty, d = exgcd(b, a % b, tx, ty);
		x = ty, y = tx - ty * (a / b);
		return d;
	}
}

int main() {
	LL a, b, c, x1, y1, x2, y2;
	scanf("%lld%lld%lld%lld%lld%lld%lld", &a, &b, &c, &x1, &y1, &x2, &y2);
	c = -c;
	if(a == 0 && b == 0) {
		if(c == 0) printf("%lld\n", (y2 - x2 + 1) * (y1 -x1 + 1));
		else printf("0\n");
		return 0;
	} else if(a == 0) {
		if(c % b == 0 && c / b >= x2 && c / b <= y2) printf("%lld\n", y1 - x1 + 1);
		else printf("0\n");
		return 0;
	} else if(b == 0) {
		if(c % a == 0 && c / a >= x1 && c / a <= y1) printf("%lld\n", y2 - x2 + 1);
		else printf("0\n");
		return 0;
	}
	if(x1 > y1 || x2 > y2) {printf("0\n"); return 0;}
	if(a < 0) {a = -a, x1 = -x1, y1 = -y1; swap(x1, y1);}
	if(b < 0) {b = -b; x2 = -x2, y2 = -y2; swap(x2, y2);}
	LL x, y, d = exgcd(a, b, x, y);
	if(c % d != 0) {printf("0\n"); return 0;}
	b /= d, a /= d; c /= d;
	x = (x * c);
	y = (y * c);
	LL l1 = 0, r1 = 0, l2 = 0, r2 = 0;
	if(x < x1) x += b * ((x1 - x + b - 1) / b);
	else x -= b * ((x - x1) / b);
	l1 = x, r1 = x + b * ((y1 - x) / b);
	if(y < x2) y += a * ((x2 - y + a - 1) / a);
	else y -= a * ((y - x2) / a);
	l2 = y, r2 = y + a * ((y2 - y) / a);
	l1 = _max(l1, (c - r2 * b) / a), r1 = _min(r1, (c - l2 * b) / a);
	if(l1 > r1) printf("0\n");
	else printf("%lld\n", (r1 - l1) / b + 1);
	return 0;
}

你可能感兴趣的:(数论,xgc的做题记录)