扩展中国剩余定理

#include<cstdio>
using namespace std;
#define ll long long
ll Left[10+5],M[10+5];
ll exgcd(ll a,ll b,ll &x,ll &y){
    if(!b){x=1,y=0;return a;}
    ll re=exgcd(b,a%b,x,y),tmp=x;
    x=y,y=tmp-(a/b)*y;
    return re;
}
int main(){
    int n,a;
    while(scanf("%d%d",&n,&a)==2&&n){
        for(int i=0;i<n;i++){
            scanf("%I64d",&M[i]);
            Left[i]=M[i]-a;
        }
        bool ok=true;ll x,y;
        for(int i=1;i<n;i++){
            ll c=Left[i]-Left[i-1];
            ll d=exgcd(M[i-1],M[i],x,y);
            if(c%d){
                ok=false;
                break;
            }
            x*=c/d;
            ll t=M[i]/d;
            x=(x%t+t)%t;
            M[i]=M[i-1]*t;
            Left[i]=(Left[i-1]+x*M[i-1])%M[i];
        }
        if(Left[n-1]) printf("%I64d
",Left[n-1]);
        else printf("%I64d
",M[n-1]);
    }
}
原文地址:https://www.cnblogs.com/033000-/p/10130739.html