中国剩余定理

中国剩余定理

看介绍和解方程:

前提:

MiM_{i}互质

例题:POJ1006

代码:

#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long ll;
const int maxn=1e4+10;
ll ExGcd(ll a,ll b,ll &x,ll &y)//求 a b 最大公约数,且得到gcd(a,b)=x*a+y*b;
{
    if(!b)
    {
        x=1;
        y=0;
        return a;
    }
    ll gcd=ExGcd(b,a%b,x,y);
    ll temp,k;
    k=a/b;
    temp=x;
    x=y;
    y=temp-k*y;
    return gcd;
}
/*

前提 mi互质
中国剩余定理
x=a1(mod m1)
x=a2(mod m2)
x=an(mod mn)
设M为m1...mn大的乘积
Mi=M/mi
设ti为Mi关于mi的逆元
则 ans=ai*Mi*ti 时间复杂度为O(n*gcd)
*/
ll aa[maxn],mm[maxn];
ll CRT(int n)//n个方程 返回x的的值
{
    ll Mpro=1;
    for(int i=0; i<n; ++i)
        Mpro*=mm[i];
    ll ans=0;
    for(int i=0; i<n; ++i)
    {
        aa[i]%=mm[i];
        ans+=(aa[i]*calc(Mpro/mm[i],1,mm[i])%Mpro*(Mpro/mm[i]))%Mpro;
    }
    return ans;
}
int main()
{
    ll a,b,c,d;
    mm[0]=23,mm[1]=28,mm[2]=33;
    int cas=0;
    ll ans=0;
    while(cin>>a>>b>>c>>d)
    {
        if(a==-1)
            break;
        aa[0]=a;
        aa[1]=b;
        aa[2]=c;
        ans=CRT(3);
        ll Mpro=23*28*33;
        ans=((ans-d)%Mpro+Mpro)%Mpro;
        cout<<"Case "<<++cas<<": the next triple peak occurs in ";
        cout<<(ans==0?Mpro:ans)<<" days."<<endl;
    }
    return 0;
}

原文地址:https://www.cnblogs.com/dchnzlh/p/10427226.html