3239: Discrete Logging
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 395 Solved: 252
[Submit][Status][Discuss]
Description
Given a prime P, 2 <= P < 231, an integer B, 2 <= B < P, and an integer N, 2 <= N < P, compute the discrete logarithm of N, base B, modulo P. That is, find an integer L such that
BL == N (mod P)
Input
Read several lines of input, each containing P,B,N separated by a space,
Output
for each line print the logarithm on a separate line. If there are several, print the smallest; if there is none, print “no solution”.
The solution to this problem requires a well known result in number theory that is probably expected of you for Putnam but not ACM competitions. It is Fermat’s theorem that states
BP−1 == 1 (mod P)
for any prime P and some other (fairly rare) numbers known as base-B pseudoprimes. A rarer subset of the base-B pseudoprimes, known as Carmichael numbers, are pseudoprimes for every base between 2 and P-1. A corollary to Fermat’s theorem is that for any m
B−m == BP−1−m (mod P) .
Sample Input
5 2 1
5 2 2
5 2 3
5 2 4
5 3 1
5 3 2
5 3 3
5 3 4
5 4 1
5 4 2
5 4 3
5 4 4
12345701 2 1111111
1111111121 65537 1111111111
Sample Output
0
1
3
2
0
3
1
2
0
no solution
no solution
1
9584351
462803587
HINT
Source
【题解】【BSGS模板题】
BSGS算法见:
[http://blog.csdn.net/reverie_mjp/article/details/51233630]
#include<map>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
long long p,b,n;
long long ans;
map<long long,long long>mp;
inline long long poww(long long x,long long q)
{
if (q==0) return 1;
if (q==1) return x%p;
if (q==2) return x*x%p;
if (q%2==0)
return poww(poww(x,q/2),2)%p;
else
return poww(poww(x,q/2),2)*x%p;
}
int main()
{
long long i,j;
while (scanf("%I64d%I64d%I64d",&p,&b,&n)==3)
{
if (b%p==0)
{printf("no solution\n"); continue;}
long long m,sum=0,k,x;
bool t=false;
mp.clear();
m=ceil(sqrt((double)p));//sqrt在C++中是实数类型的函数,所以里面要进行计算的数据必须要是float或double类型的
n%=p;
sum=n; mp[sum]=0;
for (j=1;j<=m;++j)
{
sum=sum*b%p;
mp[sum]=j;
}
sum=1;
x=poww(b,m);
for (i=1;i<=m;++i)
{
sum=sum*x%p;
if (mp[sum])
{t=true; k=mp[sum]; break;}
}
ans=i*m-k;
if (!t)
printf("no solution\n");
else
printf("%I64d\n",(ans%p+p)%p);
}
return 0;
}//BSGS模板题