【模板】中国剩余定理

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

#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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值