数论:中国剩余定理(CRT)

点击查看折叠代码块
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
typedef long long ll;
int n;
ll a[maxn],b[maxn],c[maxn];
ll Mul = 1;

ll exgcd(ll a,ll b,ll &x,ll &y){
    if(!b){x=1;y=0;return a;}
    ll g = exgcd(b,a%b,x,y);
    ll tx=x;
    x=y;
    y=tx-(a/b)*y;
    return g;
}

int main(){
    cin>>n;
    for (int i=1;i<=n;i++){
        scanf("%lld %lld",&a[i],&b[i]);
        Mul*=a[i];
    }
    ll ans=0;
    for (int i=1;i<=n;i++){
        c[i] = Mul / a[i];
        ll x=0,y=0;
        exgcd(c[i],a[i],x,y);
        ans+=b[i]*c[i]*(x<0?x+a[i]:x);
    }
    cout<<ans % Mul<<endl;
    return 0;
}
posted @ 2020-07-28 20:08  wsl_lld  阅读(71)  评论(0编辑  收藏  举报