1. 程式人生 > >BZOJ3239Discrete Logging——BSGS

BZOJ3239Discrete Logging——BSGS

sin aps return spa clear end fin scan lld

題目大意:給出$P,B,N$,求最小的正整數$L$,使$B^L\equiv N(mod\ P)$。

$BSGS$模板題。

#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<cstdio>
#include<vector>
#include<bitset>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
int T,k;
ll y,z,p;
ll G;
map<ll,int>ind;
ll quick(ll x,ll y,ll mod)
{
	ll res=1ll;
	while(y)
	{
		if(y&1)
		{
			res=res*x%mod;
		}
		x=x*x%mod;
		y>>=1;
	}
	return res;
}
void solve()
{
	ll n=ceil(sqrt(p));
	if(y%p==0&&z)
	{
		printf("no solution\n");
		return ;
	}
	ind.clear();
	ll sum=z%p;
	ind[sum]=0;
	for(ll i=1;i<=n;i++)
	{
		sum=sum*y;
		sum%=p;
		ind[sum]=i;
	}
	sum=quick(y,n,p);
	ll num=1ll;
	for(int i=1;i<=n;i++)
	{
		num*=sum,num%=p;
		if(ind.find(num)!=ind.end())
		{
			printf("%lld\n",((n*i-ind[num])%p+p)%p);
			return ;
		}
	}
	printf("no solution\n");
}
int main()
{
	while(scanf("%lld%lld%lld",&p,&y,&z)!=EOF)
	{
		solve();
	}
}

BZOJ3239Discrete Logging——BSGS