【模板】中国剩余定理

此模板封装了中国剩余定理等函数,支持同余方程插入。

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define FOR(i,x,y) for(int i=(x);i<=(y);i++)
#define DOR(i,x,y) for(int i=(x);i>=(y);i--)
typedef long long LL;
using namespace std;
 
struct CRT     //Chinese Remainder Theorem
{
    LL A,P;    //一个数模P为A
    CRT(){A=0,P=1;}
    LL gcd(LL a,LL b){return !b?a:gcd(b,a%b);} //欧几里得(最大公约数)
    void exgcd(LL a,LL b,LL &x,LL &y)  //扩展欧几里得(求ax+by=gcd(a,b)x的一个特解)
    {
        if(b==0){x=1,y=0;return;}
        exgcd(b,a%b,y,x);y-=a/b*x;
        return;
    }
    LL Exgcd(LL a,LL b,LL c)  //求ax+by=c x的最小非负整数解
    {
        LL g=gcd(a,b);
        if(c%g)return -1;
        a/=g,b/=g,c/=g;
        LL x,y;
        exgcd(a,b,x,y);
        return ((x*c%b)+b)%b;
    }
    void kase_insert(CRT x)
    {
        LL K=Exgcd(P,x.P,x.A-A);
        //if(K==-1)...
        A+=P*K;
        P=(P*x.P)/gcd(P,x.P);
        return;
    }
    void Read()
    {
        scanf("%lld%lld",&P,&A);
        return;
    }
    LL ask(){return A?A:P;}
}crt;
 
int main()
{
    int m;
    scanf("%d",&m);
    FOR(i,1,m)
    {
        CRT x;
        x.Read();
        crt.kase_insert(x);
    }
    printf("%lld\n",crt.ask());
    return 0;
}

猜你喜欢

转载自blog.csdn.net/paulliant/article/details/80352614