中国剩余定理

#include<bits/stdc++.h>
#define ll long long
#define gc getchar
inline ll read(){ll x = 0; char ch = gc(); bool positive = 1;for (; !isdigit(ch); 
ch = gc()) if (ch == '-')  positive = 0;for (; isdigit(ch); ch = gc())  x = x * 10 
+ ch - '0';return positive ? x : -x;}inline void write(ll a){if(a>=10)write(a/10);
putchar('0'+a%10);}inline void writeln(ll a){if(a<0){a=-a; putchar('-');}write(a);
puts("");}
using namespace std;
const int N = 11;
ll l,r,n;
ll m[N], M = 1,a[N], Mi;
void exgcd(ll a,ll b,ll &x , ll &y) {
	if(b) {
		exgcd(b, a % b, y, x);
		y -= a / b * x;
	}else {
		x = 1;
		y = 0;
	}
}
int main() {
	ll x, y, res = 0, ans = 0;
	n = read(), l = read(),r = read();
	for(int i = 1; i <= n; ++i)
		m[i] = read(), a[i] = read(), M *= m[i];
	for(int i = 1; i <= n; ++i) {
		Mi = M / m[i];
		exgcd(Mi, m[i], x, y);
		x = (x % m[i] + m[i]) % m[i];
		res = res + a[i] * Mi * x ;
	}
	res %= M;
	if(!res) res += M;
	if(res < l) res += (l - res - 1) / M * M + M;
	if(res <= r) ans = (r - res - 1) / M + 1;
	if(!ans) {
		puts("0\n0");
		return 0;
	}
	writeln(ans);
	writeln(res);
	return 0;
}
posted @ 2018-04-16 18:40  绍兴土匪  阅读(191)  评论(0编辑  收藏  举报