码迷,mamicode.com
首页 > 其他好文 > 详细

同余方程组(EXCRT)(luogu4777)

时间:2018-12-14 22:53:35      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:mod   info   mes   gcd   algo   pre   ima   方程组   \n   

技术分享图片

#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
ll k;
ll a1,r1;
ll a2,r2;
ll x,y;
ll g;
void init()
{
    scanf("%lld",&k);
}
void exgcd(ll a,ll b)
{
    if(b==0)
    {
        x = 1;
        y = 0;
    }else
    {
        exgcd(b,a%b);
        ll t = x;
        x = y;
        y = t-a/b*x;
    }
}
void gcd(ll x,ll y)
{
    if(y==0)
    {
        g = x;
        return ;
    }
    gcd(y,x%y);
}
ll ksc(ll x,ll y,ll mod)
{
    ll ans = 0,kk=1;
    if(x<0)x=-x,kk=-kk;
    if(y<0)y=-y,kk=-kk;
    while(y)
    {
        if(y%2)
        {
            ans = (ans+x)%mod;
        }
        y>>=1;
        x = (x+x)%mod;    
    }
    return ans%mod*kk;
}
void solve()
{
    scanf("%lld%lld%lld%lld",&a1,&r1,&a2,&r2);
    ll a,b,c;
    a = a1;
    b = a2;
    c = r2-r1;//ax=c(mod b)
    gcd(a,b);
    if(c%g!=0)
    {
        printf("-1\n");
        return ;
    }
    a = a/g;
    b = b/g;
    c = c/g;
    exgcd(a,b);
     x = (ksc(x,c,b)+b)%b;//x = k0
     c = x*a1+r1;
     gcd(a1,a2);
     b = a1/g*a2;
     k = k-2;
     r1 = c;
     a1 = b;
     while(k--)
     {
         scanf("%lld%lld",&a2,&r2);
         ll a,b,c;
        a = a1;
        b = a2;
        c = r2-r1;//ax=c(mod b)
        gcd(a,b);
        if(c%g!=0)
        {
            printf("-1\n");
            return ;
        }
        a = a/g;
        b = b/g;
        c = c/g;
        exgcd(a,b);
         x =(ksc(x,c,b)+b)%b;//x = k0
         c = x*a1+r1;
         gcd(a1,a2);
         b = a1/g*a2;
         r1 = c;
         a1 = b;
    }
    exgcd(1,a1);
    x = (ksc(x,r1,a1)+a1)%a1;
    printf("%lld\n",x);
}
int main()
{
    init();
    solve();
    return 0;
}

 

同余方程组(EXCRT)(luogu4777)

标签:mod   info   mes   gcd   algo   pre   ima   方程组   \n   

原文地址:https://www.cnblogs.com/lizitong/p/10121573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!