POJ2891 扩展中国剩余定理

最后输出写反了调了半天。。。醉了。。。

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int N=1e6+5;
typedef long long ll;
ll a[N],b[N];
ll gcd(ll a,ll b)
{return !b?a:gcd(b,a%b);}
void exgcd(ll a,ll b,ll &x,ll &y)
{
    if(b==0)
    {
        x=1,y=0;
        return ;
    }
    exgcd(b,a%b,y,x);
    y-=(a/b)*x;
}
ll mul(ll a,ll b,ll p)
{
    ll res=0;
    while(b)
    {
        if(b&1)
            res=(res+a)%p;
        b>>=1;
        a=(a+a)%p;
    }
    return res;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        int flag=1;
        for(int i=1;i<=n;i++) scanf("%lld%lld",&a[i],&b[i]);
        ll ans=0,m=1,x,y;
        for(int i=1;i<=n;i++)
        {
            exgcd(m,a[i],x,y);
            ll g=gcd(m,a[i]),c=((b[i]-ans)%a[i]+a[i])%a[i];
            if(c%g) 
            {
                flag=0;
                break;
            }
            x=mul(x,c/g,a[i]/g);
            ans+=x*m;
            m=m/g*a[i];
            ans=(ans%m+m)%m;
        }
        flag? printf("%lld\n",ans==0?m:ans) :puts("-1");//-1代表无解,ans==0输出最小公倍数
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值