P4777 【模板】扩展中国剩余定理(EXCRT)

题目链接

题面:
在这里插入图片描述

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<map>
#define ll long long
using namespace std;
const int maxn=100010;
ll a[maxn],m[maxn];
int k;
ll q_pow(ll a,ll b,ll p)
{
    ll ans=0;
    while(b)
    {
        if(b&1) ans=(ans+a)%p;
        a=(a+a)%p;
        b>>=1;

    }
    return ans%p;
}

ll mypow(ll a,ll b,ll p)
{
    ll ans=1;
    while(b)
    {
        if(b&1) ans=q_pow(ans,a,p);
        a=q_pow(a,a,p);
        b>>=1;
    }
    return ans;
}

ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(b==0)
    {
        x=1;
        y=0;
        return a;
    }

    ll d=exgcd(b,a%b,x,y);

    ll z=x;
    x=y;
    y=z-a/b*y;
    return d;
}

ll china(void)
{
    ll ans=a[1];
    ll x,y;
    ll M=m[1];
    for(int i=2;i<=k;i++)
    {

        ll c=(a[i]-ans%m[i]+m[i])%m[i];

        ll d=exgcd(M,m[i],x,y);
        if(c%d!=0) return -1;

        x=q_pow(x,c/d,m[i]/d);

        ans=(ans+x*M);
        M=M*(m[i]/d);
        ans=(ans%M+M)%M;
    }
    return (ans%M+M)%M;
}




int main(void)
{

    scanf("%d",&k);

    for(int i=1;i<=k;i++)
    {
        scanf("%lld%lld",&m[i],&a[i]);
    }

    printf("%lld\n",china());
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值