中国剩余定理
2016-07-13 11:08
411 查看
中国剩余定理:求解一次同余式组
对于特殊的中国剩余定理:即要求m[1],m[2].....m
两两互素
int fun(int a[], int m[], int n){ int M = 1; int i; for(i=0; i<n; i++){ M *= m[i]; } int X = 0; for(i=0; i<n; i++){ int x, y; int Mi = M/m[i]; exgcd(Mi, m[i], x, y); X = (X + a[i]*Mi*x) % M; } if(X<0) X += M; return X; }
例:poj-1006 http://poj.org/problem?id=1006
题目大意:人自出生起就有体力,情感和智力三个生理周期,分别为23,28和33天。一个周期内有一天为峰值,通常这三个周期的峰值不会是同一天。
现在给出三个日期,分别对应体力、情感、智力出现等值的日期,给定一个从当年第一天开始数的天数,输出从给定时间开始(不包括给定时间)下一次
三个高峰落在同一天的时间(距给定时间的天数)。
附代码:
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> using namespace std; int m[4] = {23, 28, 33}; int a[4]; void exgcd(int a, int b, int &x, int &y){ //求逆元 if(b==0){ x = 1; y = 0; return ; } exgcd(b, a%b, x, y); int t = x; x = y; y = t-a/b*y; return; } int fun(int a[], int m[], int n){ //中国剩余定理 int M = 1; int i; for(i=0; i<n; i++){ M *= m[i]; } int X = 0; for(i=0; i<n; i++){ int x, y; int Mi = M/m[i]; exgcd(Mi, m[i], x, y); X = (X + a[i]*Mi*x) % M; } if(X<0) X += M; return X; } int main(){ int i, j, k, d, cas = 1; while(cin>>a[0]>>a[1]>>a[2]>>d){ if(a[0]==a[1]&&a[1]==a[2]&&a[2]==d&&d==-1) break; int ans = fun(a,m,3); if(ans<d) ans += 21252; //cout<<ans-d<<endl; printf("Case %d: the next triple peak occurs in %d days.\n",cas++, ans-d); } return 0; }
对于一般形式的中国剩余定理:
相关文章推荐
- 中国剩余定理
- 中国剩余定理
- 中国剩余定理介绍
- ZOJ1160 Biorhythms【中国剩余定理】
- 同余 模算术 中国剩余定理
- 洛谷P2480 [SDOI2010]古代猪文(费马小定理,卢卡斯定理,中国剩余定理,线性筛)
- 曹冲养猪 中国剩余定理
- 中国剩余定理求解“六位教授必须首次都停止上课”问题
- 【HDU 3430】中国剩余定理
- poj1006_Biorhythms_扩展欧几里得_中国剩余定理
- HDU 5446 中国剩余定理+lucas
- 理解中国剩余定理
- HDU 5446-Unknown Treasure(Lucas+中国剩余定理)
- HDU5446 Unknown Treasure Lucas+中国剩余定理
- hdu5446 lucas+中国剩余定理
- hdu5446 Unknown Treasure(Lucas+中国剩余定理)
- Codeforces 338D GCD Table 中国剩余定理
- poj 1006 中国剩余定理模板
- 中国剩余定理(同余方程组)小结
- 中国剩余定理