1. 程式人生 > 其它 >P4777 【模板】擴充套件中國剩餘定理(EXCRT)

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; }