标签:
设n>=2,m1,m2,....mn,是两两互质的正整数,记 M = ∏mi, Mi = M/mi.
则同余方程组
X≡a1(mod m1)
X≡a2 (mod m2)
X≡an (mod mn)
有对模M的唯一解
X≡∑aiMiMi’(mod M)
上述就是中国剩余定理
下面给出求此类同余方程组最小非负整数解的代码 LL 代表 long long
1 LL China(LL r) 2 { 3 LL M = 2; 4 LL i,Mi,x0,y0,d,ans = 0; 5 for(i=1;i<=r;i++){ 6 M *= m[i]; 7 } 8 for(i=1;i,=r;i++){ 9 Mi = M/m[i]; 10 ex_gcd(Mi,m[i],x0,y0); 11 ans = (ans+Mi*x0*a[i])%M; 12 } 13 if(ans < 0) ans += M; 14 return ans; 15 }
然后以poj1006 这个题目来练一下手 链接 http://poj.org/problem?id=1006
根据题意可以得到同余方程组 X≡p(mod 23)
X≡e(mod 28)
X≡i(mod 33)
注意到 23 28 33是两两互质整数,满足中国剩余定理的使用条件,根据上面给出的代码容易解决,题目所求得解释大于d的最小整数解
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <stack> 5 #include <queue> 6 #include <map> 7 #include <algorithm> 8 #include <vector> 9 10 using namespace std; 11 12 const int maxn = 1000005; 13 14 typedef long long LL; 15 16 LL a[20],m[8],M; 17 18 LL ex_gcd(LL a,LL b,LL &x,LL &y) 19 { 20 if(b == 0){ 21 x = 1; 22 y = 0; 23 return a; 24 } 25 LL r = ex_gcd(b,a%b,x,y); 26 LL t = x; 27 x = y; 28 y = t - a/b*y; 29 return r; 30 } 31 LL China(LL r) 32 { 33 M = 1; 34 LL i,Mi,x0,y0,d,ans = 0; 35 for(i=1;i<=r;i++){ 36 M *= m[i]; 37 } 38 for(i=1;i<=r;i++){ 39 Mi = M/m[i]; 40 ex_gcd(Mi,m[i],x0,y0); 41 ans = (ans+Mi*x0*a[i])%M; 42 } 43 if(ans < 0) ans += M; 44 return ans; 45 } 46 47 int main() 48 { 49 int cas = 0; 50 LL p,e,i,d,temp; 51 while(scanf("%lld%lld%lld%lld",&p,&e,&i,&d)!=EOF){ 52 cas++; 53 if(p==-1&&e==-1&&i==-1&&d==-1) break; 54 a[1] = p; 55 a[2] = e; 56 a[3] = i; 57 m[1] = 23; 58 m[2] = 28; 59 m[3] = 33; 60 LL r = 3; 61 LL ans = China(r); 62 while(ans <= d) ans += M; 63 printf("Case %d: the next triple peak occurs in %lld days.\n",cas,ans-d); 64 } 65 66 67 return 0; 68 }
标签:
原文地址:http://www.cnblogs.com/lmlyzxiao/p/4934353.html