其他分享
首页 > 其他分享> > P4195 【模板】exBSGS/Spoj3105 Mod

P4195 【模板】exBSGS/Spoj3105 Mod

作者:互联网

题目链接:https://www.luogu.org/problem/P4195
AC代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a,p,b,x;
map<ll,ll>hashmp;
ll gcd(ll x,ll y)
{
    return (y==0?x:gcd(y,x%y));
}
ll qpow(ll x,ll y,ll mo)
{
    ll ans=1;
    while(y){
        if(y&1){
            ans=ans*x%mo;
        }
        x=x*x%mo;
        y>>=1;
    }
    return ans;
}
void exBSGS(ll a,ll p,ll b)
{
    if(b==1){
        printf("0\n");
        return ;
    }
    hashmp.clear();
    ll k=0;
    ll xishu=1;
    ll tgcd=gcd(a,p);
    while(tgcd!=1){
        if(b%tgcd!=0){
            printf("No Solution\n");
            return ;
        }
        xishu=xishu*(a/tgcd)%p;
        k++;
        b=b/tgcd;
        p=p/tgcd;
        tgcd=gcd(a,p);
    }
    ll m=ceil(sqrt(p));
    ll tmpb=b%p;
    hashmp[tmpb]=0;
    for(ll j=1;j<=m;j++){
        tmpb=tmpb*a%p;
        hashmp[tmpb]=j;
    }
    ll tmpa=xishu;
    ll ma=qpow(a,m,p);
    ll tt=0;
    for(ll i=1;i<=m;i++){
        tmpa=tmpa*ma%p;
        tt=hashmp[tmpa];
        if(tt){
            ll ans=i*m-tt+k;
            printf("%lld\n",ans);
            break;
        }
    }
    if(tt==0)
        printf("No Solution\n");
    return ;
}
int main()
{
    while(~scanf("%lld%lld%lld",&a,&p,&b)){
        if((a+b+p)==0){
            break;
        }
        exBSGS(a,p,b);
    }
    return 0;
}

标签:return,gcd,ll,tgcd,ans,xishu,P4195,exBSGS,Mod
来源: https://blog.csdn.net/weixin_43499182/article/details/98241360