P4777 【模板】扩展中国剩余定理(EXCRT)

【题意】

求多个同余方程的解,不保证模数互质

【分析】

 

分析

【代码】

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
int n;
ll A[maxn],B[maxn];
ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(!b)
    {
        x=1; y=0; return a;
    }
    ll gcd=exgcd(b,a%b,x,y);
    ll tmp=x;
    x=y; y=tmp-a/b*y;
    return gcd;
}
ll mul(ll a,ll b,ll mod)
{
    ll res=0;
    while(b)
    {
        if(b&1) res=(res+a)%mod;
        a=(a+a)%mod;
        b>>=1;
    }
    return res;
}
ll excrt()
{
    ll M=A[1],ans=B[1],x,y;
    for(int i=2;i<=n;i++)
    {
        ll a=M,b=A[i],c=(B[i]-ans%b+b)%b;
        ll g=exgcd(a,b,x,y);
        ll bg=b/g;
        if(c%g!=0) return -1;
        x=mul(x,c/g,bg);
        ans+=x*M; M=M*bg; 
        ans=(ans%M+M)%M;
    }
    return ans;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%lld%lld",&A[i],&B[i]);
    printf("%lld\n",excrt());
    return 0;
}

 

posted @ 2021-06-29 13:56  andyc_03  阅读(40)  评论(0编辑  收藏  举报