中国剩余定理

来源:互联网 发布:桌面上软件打不开 编辑:程序博客网 时间:2024/06/06 16:32

任务:求出方程组x≡ai (mod mi) (0<=i<n) 的解 x

其中m_0, m_1,m_2, ... , m_{n-1}两两互质

使用范例:[POJ1006](http://poj.org/problem?id=1006)


#include<iostream>#include<vector>using namespace std;typedef long long LL;LL a[5],m[5];//ax+by=gcd(a,b)LL extend_gcd(LL a,LL b,LL &x,LL &y){    if(b==0)    {        x=1;y=0;        return a;    }else    {        LL r=extend_gcd(b,a%b,y,x);        y-=x*(a/b);        return r;    }}//x≡ai(mod mi) (0<=i<n)//复杂度 O(nlogm) m和每个mi同阶LL CRT(LL a[],LL m[],LL n){    LL M=1;    for(LL i=0;i<n;i++)        M*=m[i];    LL ret=0;    for(LL i=0;i<n;i++)    {        LL x,y;        LL tm=M/m[i];        //tm*x+m[i]*y=gcd(tm,m[i])=1;        //tm*x≡1 (mod m[i]) 求逆元        extend_gcd(tm,m[i],x,y);        ret=(ret+tm*x*a[i])%M;    }    return (ret+M)%M;}int main(){    LL d;    m[0]=23;m[1]=28;m[2]=33;    int cas=1;    while(cin>>a[0]>>a[1]>>a[2]>>d)    {        if(a[0]==-1&&a[1]==-1&&a[2]==-1&&d==-1) break;        LL ans=CRT(a,m,3)-d;        if(ans<=0) ans+=21252;        cout<<"Case "<<cas++<<": the next triple peak occurs in "<<ans<<" days."<<endl;    }    return 0;}


0 0
原创粉丝点击