Ex-BSGS
给定,求的最小自然数 .
保证
当时,表示输入数据完成。
#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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】