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輸出最小公倍數
    }
}

 

發佈了74 篇原創文章 · 獲贊 4 · 訪問量 5057
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章