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

BSGS(Baby Steps,Giant Steps)

时间:2019-08-01 20:12:38      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:typedef   code   def   find   i++   ceil   quick   eps   print   

技术图片

技术图片

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
ll n,m,y,z,p,x,ans,block;
map<ll,int>mp;

ll quick(ll a,ll b,ll p)
{
    ll res=1%p;
    while (b)
    {
        if (b&1)
        {
            res=res*a%p;
        }
        a=a*a%p;
        b=b>>1;
    }
    return res;
}

void solve1()
{
    for (int i=1; i<=n; i++)
    {
        scanf("%lld%lld%lld",&y,&z,&p);
        y=y%p;
        printf("%lld\n",quick(y,z,p));
    }
}

void solve2()
{
    for (int i=1; i<=n; i++)
    {
        scanf("%lld%lld%lld",&y,&z,&p);
        y%=p;
        z%=p;
        if (y==0&&z!=0)
        {
            printf("Orz, I cannot find x!\n");
        }
        else
        {
            printf("%lld\n",z*quick(y,p-2,p)%p);
        }
    }
}

void solve3()
{

    for (int i=1; i<=n; i++)
    {
        scanf("%lld%lld%lld",&y,&z,&p);
        ans=-1;
        mp.clear();
        y=y%p;
        if (y==0&&z==0)
        {
            printf("1\n");
            continue;
        }
        if (y==0)
        {
            printf("Orz, I cannot find x!\n");
            continue;
        }
        block=ceil(sqrt(p));
        ll num=z;
        for (int j=0; j<=block; j++)
        {
            mp[num]=j+1;
            num=num*y%p;
        }
        ll sum=quick(y,block,p);
        num=sum;
        for (int j=1; j<=block; j++)
        {
            if (mp[num%p])
            {
                if (mp[num%p]==-1) ans=0;
                else
                {
                    ans=j*block-mp[num]+1;
                }
                break;
            }
            num=num*sum%p;
        }
        if (ans==-1)
        {
            printf("Orz, I cannot find x!\n");
        }
        else
        {
            printf("%lld\n",ans);
        }
    }
}

int main()
{
    scanf("%lld%lld",&n,&m);
    if (m==1)
    {
        solve1();
    }
    if (m==2)
    {
        solve2();
    }
    if (m==3)
    {
        solve3();
    }
}

  

BSGS(Baby Steps,Giant Steps)

标签:typedef   code   def   find   i++   ceil   quick   eps   print   

原文地址:https://www.cnblogs.com/Accpted/p/11284874.html

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