洛谷 P3846 [TJOI2007] 可爱的质数/【模板】BSGS(大步小步算法)

传送门


解题思路

暴力枚举指数的复杂度是 \(O(p)\) 的(费马小定理)
所以用分块思想。
\(l\) 分成 \(\sqrt p\) 块,每块的长度为 \(\sqrt p\)
先预处理出 \(i=1\to \sqrt p\)\(b^i\bmod p\) 的值,开个map存下值所对应的指数i。
再枚举第 \(j\) 块,设

\[b^{j\times\sqrt q+i}\equiv n\pmod p \]

只需要把其转化为:

\[b^i\equiv n \times (b^{j\times \sqrt q})^{-1}\pmod p \]

用map判断一下即可。
总复杂度 \(O(\sqrt p)\)

AC代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iomanip>
#include<vector>
#include<ctime>
#include<set>
#include<queue>
#include<stack>
#include<algorithm>
#include<map>
using namespace std;
template<class T>inline void read(T &x)
{
    x=0;register char c=getchar();register bool f=0;
    while(!isdigit(c))f^=c=='-',c=getchar();
    while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar();
    if(f)x=-x;
}
template<class T>inline void print(T x)
{
    if(x<0)putchar('-'),x=-x;
    if(x>9)print(x/10);
    putchar('0'+x%10);
}
long long n,b,p;
long long ksm(long long a,long long b){
	if(b==0) return 1;
	if(b==1) return a;
	long long res=ksm(a,b/2);
	if(b&1) return res*res%p*a%p;
	return res*res%p;
}
inline long long inv(long long a){
	return ksm(a,p-2);
}
map<long long,long long> ma;
int main(){
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	ios::sync_with_stdio(false);
	cin>>p>>b>>n;
	long long sqr=sqrt(p);
	for(long long i=0;i<=sqr;i++) ma[ksm(b,i)]=i;
	for(long long i=0;i*sqr<=p;i++){
		long long j=i*sqr;
		long long res=n*inv(ksm(b,j))%p;
		if(ma.find(res)!=ma.end()){
			cout<<j+ma[res]<<endl;
			return 0;
		}
	}
	cout<<"no solution"; 
	return 0;
}
posted @ 2021-10-08 09:02  尹昱钦  阅读(80)  评论(0编辑  收藏  举报