基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
一个正整数K,给出K Mod 一些质数的结果,求符合条件的最小的K。例如,K % 2 = 1, K % 3 = 2, K % 5 = 3。符合条件的最小的K = 23。
Input
第1行:1个数N表示后面输入的质数及模的数量。(2 <= N <= 10) 第2 - N + 1行,每行2个数P和M,中间用空格分隔,P是质数,M是K % P的结果。(2 <= P <= 100, 0 <= K < P)
Output
输出符合条件的最小的K。数据中所有K均小于10^9。
Input示例
3 2 1 3 2 5 3
Output示例
23
中国剩余定理(CRT)的表述如下
设正整数两两互素,则同余方程组
有整数解。并且在模下的解是唯一的,解为
其中,而
为
模
的逆元。
//chu是除数,yu是余数
//注意只适用于除数两两互质
#include<iostream>
#include<queue>
using namespace std;
typedef long long ll;
ll extended_euclid(ll a, ll b, ll &x, ll &y) {
ll d;
if(b == 0) {x = 1; y = 0; return a;}
d = extended_euclid(b, a % b, y, x);
y -= a / b * x;
return d;
}
ll chinese_remainder(ll b[], ll w[], ll len) {
ll i, d, x, y, m, n, ret;
ret = 0; n = 1;
for(i=0; i < len ;i++) n *= w[i];
for(i=0; i < len ;i++) {
m = n / w[i];
d = extended_euclid(w[i], m, x, y);
ret = (ret + y*m*b[i]) % n;
}
return (n + ret%n) % n;
}
ll yu[100],chu[100];
int main()
{
ll n;
while(cin>>n)
{
for(ll i=0;i<n;i++)
{
cin>>chu[i]>>yu[i];
}
ll ans=chinese_remainder(yu,chu,n);
cout<<ans<<endl;
}
return 0;
}