中国剩余定理 vijos1164 曹冲养猪

传送门:点击打开链接

中国剩余定理的第一个模板。

这个模板比较简单,求的是一系列的模方程组

x % m = a


用这个模板有几个前提。

1:必须两两互质

2:全部乘起来不能爆long long

#include<map>
#include<set>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define FIN freopen("input.txt","r",stdin)

using namespace std;
typedef long long LL;
typedef pair<int, int> PII;

const int MX = 1000 + 5;

LL exgcd(LL a, LL b, LL &x, LL &y) {
    if(b == 0) {
        x = 1; y = 0;
        return a;
    }
    LL r = exgcd(b, a % b, x, y);
    LL t = y;
    y = x - a / b * y;
    x = t;
    return r;
}

/*x % m = a*/
LL china(int n, int *m, int *a) {
    LL M = 1, d, y, x = 0;
    for(int i = 0; i < n; i++) M *= m[i];
    for(int i = 0; i < n; i++) {
        LL w = M / m[i];
        d = exgcd(m[i], w, d, y);
        x = (x + y * w * a[i]) % M;
    }
    return (x + M) % M;
}

int A[MX], B[MX];

int main() {
    FIN;
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
        scanf("%d%d", &A[i], &B[i]);
    }
    printf("%I64d\n", china(n, A, B));
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值