Ex-BSGS

给定 a , p , b a,p,b a,p,b,求 a x ≡ b ( m o d p ) a^x\equiv b \pmod p axb(modp)的最小自然数 x x x .
保证 ∑ p ≤ 5 × 1 0 6 \sum \sqrt p \leq5\times 10^6 p 5×106
a = p = b = 0 a=p=b=0 a=p=b=0时,表示输入数据完成。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<vector>
using namespace std;
typedef long long LL;
const int Hsh=10007;
LL ans,a,p,b,flg[Hsh+5];
vector<pair<LL,int> > V[Hsh+5];
LL Gcd(LL a,LL b){
    if(a%b==0) return b;
    return Gcd(b,a%b);
}
LL exbsgs(){
    memset(flg,0,sizeof(flg));
    if(!p) return -1;
    if(p==1){
        if(!b) return 0;
        return -1;
    }
    if(b==1) return 0;
    a%=p;b%=p;
    LL g=1,cnt=0,tmpb=1;
    while ((g=Gcd(a,p))>1){
        if(tmpb%p==b%p) return cnt;
        if(b%g) return -1;
        b/=g;p/=g;
        tmpb=tmpb*(a/g)%p;
        cnt++;
    }
    LL m=ceil(sqrt(double(p)));
    LL tmp=1,tmpid=0;
    for(int i=1;i<=m;i++){
        tmp=tmp*a%p;
        tmpid=(tmp*b%p)%Hsh;
        if(!flg[tmpid]){
            V[tmpid].clear();
            flg[tmpid]=1;
        }
        V[tmpid].push_back(make_pair(tmp*b%p,i));
    }
    LL res=tmpb%p,tmpres=1;
    for(int i=1;i<=m;i++){
        res=res*tmp%p;
        tmpres=res%Hsh;
        if(flg[tmpres]){
            for(int j=V[tmpres].size()-1;j>=0;j--){
                if(V[tmpres][j].first==res) return (i*m-V[tmpres][j].second)+cnt;
            }
        }
    }
    return -1;
}
int main(){
    while (scanf("%lld%lld%lld",&a,&p,&b)&&(a|p|b)!=0){
        ans=exbsgs();
        if(ans==-1) puts("No Solution");
        else printf("%lld\n",ans);
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值