您的位置:首页 > 其它

中国剩余定理的应用

2015-11-03 20:56 417 查看
设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

#include <cstdio>
#include <cstring>
#include <iostream>
#include <stack>
#include <queue>
#include <map>
#include <algorithm>
#include <vector>

using namespace std;

const int maxn = 1000005;

typedef long long LL;

LL a[20],m[8],M;

LL ex_gcd(LL a,LL b,LL &x,LL &y)
{
if(b == 0){
x = 1;
y = 0;
return a;
}
LL r = ex_gcd(b,a%b,x,y);
LL t = x;
x = y;
y = t - a/b*y;
return r;
}
LL China(LL r)
{
M = 1;
LL i,Mi,x0,y0,d,ans = 0;
for(i=1;i<=r;i++){
M *= m[i];
}
for(i=1;i<=r;i++){
Mi = M/m[i];
ex_gcd(Mi,m[i],x0,y0);
ans = (ans+Mi*x0*a[i])%M;
}
if(ans < 0) ans += M;
return ans;
}

int main()
{
int cas = 0;
LL p,e,i,d,temp;
while(scanf("%lld%lld%lld%lld",&p,&e,&i,&d)!=EOF){
cas++;
if(p==-1&&e==-1&&i==-1&&d==-1) break;
a[1] = p;
a[2] = e;
a[3] = i;
m[1] = 23;
m[2] = 28;
m[3] = 33;
LL r = 3;
LL ans = China(r);
while(ans <= d) ans += M;
printf("Case %d: the next triple peak occurs in %lld days.\n",cas,ans-d);
}

return 0;
}


View Code

      
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: