备战NOIP——模板复习26

这里只有模板,并不作讲解,仅为路过的各位做一个参考以及用做自己复习的资料,转载注明出处。

中国剩余定理(CRT)

/*Copyright: Copyright (c) 2018
*Created on 2018-11-08
*Author: 十甫
*Version 1.0 
*Title: CRT
*Time: inf mins
*/
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
const int size = 15;
typedef long long ll;

int n;
ll a[size], b[size];
inline ll add(ll a, ll b, ll p) {
    ll res = 0;
    while(b) {
        if(b & 1) res = ((res % p) + (a % p)) % p;
        a = ((a % p) + (a % p)) % p;
        b /= 2;
    }
    return res;
}
inline void ex_gcd(ll a, ll b, ll &x, ll &y, ll &d) {
    if(!b) {
        d = a, x = 1, y = 0;
        return;
    }
    ex_gcd(b, a % b, y, x, d);
    y -= (a / b) * x;
}
inline ll inv(ll a, ll b) {
    ll d, x, y;
    ex_gcd(a, b, x, y, d);
    return d == 1 ? (x % b + b) % b : -1;
}
ll CRT() {
    ll M = 1;
    for(int i = 1;i <= n;i++) {
        M *= b[i];
    }
    ll ans = 0;
    for(int i = 1;i <= n;i++) {
        ans = ((ans % M) + add(add(a[i],  M / b[i], M),  inv(M / b[i], b[i]), M) % M) % M;
    }
    return ans;
}

int main() {
    scanf("%d", &n);
    for(int i = 1;i <= n;i++) {
        scanf("%lld", &a[i]);
    }
    for(int i = 1;i <= n;i++) {
        scanf("%lld", &b[i]);
    }
    printf("%lld\n", CRT());
    return 0;
}

 

posted @ 2018-11-08 17:48  十甫  阅读(91)  评论(0编辑  收藏  举报