BSGS(Baby Steps,Giant Steps)

#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();
    }
}

  

猜你喜欢

转载自www.cnblogs.com/Accpted/p/11284874.html