中国剩余定理

来源:互联网 发布:网络电视直播手机版 编辑:程序博客网 时间:2024/06/07 23:48

POJ 1006 中国剩余定理模板


#include<iostream>
#include<stdio.h>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
const int N=10;
int a[N],m[N]={11,23,28,33};  //  x = ai (mod mi)
LL M;
void gcd(LL a,LL b, LL& d,LL& x,LL& y)
{
    if(!b){d=a;x=1;y=0;}
    else
    {
        gcd(b,a%b,d,y,x);
        y-=x*(a/b);
    }
}
LL china(int n,int a[],int m[])
{
    LL d,y,x=0;
    M=1;
    for(int i=1;i<=n;i++) M*=m[i];
    for(int i=1;i<=n;i++)
    {
        LL w = M / m[i];
        gcd(m[i],w,d,d,y);
        x = (x + y*w*a[i]) % M;
    }
    return (x+M)%M;
}
int main()
{
    int day;int cas=0;
    while(scanf("%d%d%d%d",&a[1],&a[2],&a[3],&day)!=EOF)
    {
        if(a[1]==-1) break;
        LL ans = china(3,a,m);
        ans-=day;
        if(ans<=0) ans+=M;
        printf("Case %d: the next triple peak occurs in ",++cas);
        printf("%lld",ans);
        printf(" days.\n");
    }
    return 0;
}


0 0
原创粉丝点击