中国剩余定理

一个正整数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。Sample Input

3
2 1
3 2
5 3

Sample Output

23


 1 #include<cstdio>
 2 typedef long long LL;
 3 const int N = 100000 + 5;
 4 void ex_gcd(LL a, LL b, LL &x, LL &y, LL &d)
 5 {
 6     if (!b)
 7     {
 8         d = a, x = 1, y = 0;
 9     }
10     else
11     {
12         ex_gcd(b, a % b, y, x, d);
13         y -= x * (a / b);
14     }
15 }
16 LL inv(LL t, LL p) //如果不存在,返回-1
17 {
18     LL d, x, y;
19     ex_gcd(t, p, x, y, d);
20     return d == 1 ? (x % p + p) % p : -1;
21 }
22 LL china(int n, LL *a, LL *m) //中国剩余定理
23 {
24     LL M = 1, ret = 0;
25     for(int i = 0; i < n; i ++) M *= m[i];
26     for(int i = 0; i < n; i ++)
27     {
28         LL w = M / m[i];
29         ret = (ret + w * inv(w, m[i]) * a[i]) % M;
30     }
31     return (ret + M) % M;
32 }
33 
34 int main()
35 {
36     int t,i;
37     LL p[50], r[50], d, ans, MOD = 1000000009;
38     int cas = 0;
39     scanf("%d",&t);
40     for(i=0;i<t;i++)
41     {
42         scanf("%lld%lld",&p[i],&r[i]);
43     }
44     ans = ((china(t, r, p)) % MOD + MOD) % MOD;
45     printf("%lld
",ans);
46 }
View Code
原文地址:https://www.cnblogs.com/daybreaking/p/9342641.html