中国剩余定理

今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?——《孙子算经》

这是最早的关于中国剩余定理的研究。 中国剩余定理基本不会考到,但是学习证明的过程会对群的理解很有帮助。

模板

LL ex_crt(LL *m, LL *r, int n)
{
    LL M = m[1], R = r[1], x, y, d;
    for (int i = 2; i <= n; ++i)
    {
        ex_gcd(M, m[i], d, x, y);
        if ((r[i] - R) % d) return -1;
        x = (r[i] - R) / d * x % (m[i] / d);
        R += x * M;
        M = M / d * m[i];
        R %= M;
    }
    return R > 0 ? R : R + M;
}

例题

POJ 2891 就是一道标准的中国剩余定理题目,首先判断所有m[i]是否互质,随后套用模板即可。

#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<set>
#include<cstdlib>

using namespace std;

#define LL long long
const int inf = 0x3f3f3f3f;
const int maxn = 1e5 + 5;
int n;
void ex_gcd(LL a, LL b, LL &d, LL &x, LL &y)
{
    if (!b) {d = a, x = 1, y = 0;}
    else
    {
        ex_gcd(b, a % b, d, y, x);
        y -= x * (a / b);
    }
}
LL ex_crt(LL *m, LL *r, int n)
{
    LL M = m[1], R = r[1], x, y, d;
    for (int i = 2; i <= n; ++i)
    {
        ex_gcd(M, m[i], d, x, y);
        if ((r[i] - R) % d) return -1;
        x = (r[i] - R) / d * x % (m[i] / d);
        R += x * M;
        M = M / d * m[i];
        R %= M;
    }
    return R > 0 ? R : R + M;
}
int main()
{
    while (~scanf("%d",&n))
    {
        LL m[maxn], r[maxn];
        for (int i = 1; i <= n; ++i)
            scanf("%lld%lld", &m[i], & r[i]);
        printf("%lld\n",ex_crt(m,r,n));
    }
    return 0;
}

results matching ""

    No results matching ""