Discrete Logging
Given a prime P, 2 <= P < 2 31, an integer B, 2 <= B < P, and an integer N, 1 <= 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”.
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
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
B(P-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) == B(P-1-m) (mod P) .
直接套模板
code:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <map>
using namespace std;
typedef long long ll;
ll q_pow(ll a, ll b, ll mod){
ll ans = 1;
while(b){
if(b & 1) ans = ans * a % mod;
b >>= 1;
a = a * a % mod;
}
return ans;
}
ll gcd(ll a,ll b){
return b ? gcd(b,a%b) : a;
}
void ex_gcd(ll a,ll b,ll &x,ll &y){
if(!b){
x = 1;
y = 0;
return;
}
ex_gcd(b,a%b,y,x);
y -= a / b * x;
return;
}
ll BSGS(ll a, ll b, ll p) {
a %= p; b %= p;
map<ll, ll> h;
map<ll,bool> vis;//这道题必须多加一个map作为标记,否则直接查找会超时!!
ll m = ceil(sqrt(p)), x, y, d, t = 1, v = 1;
for(ll i = 0; i < m; ++i) {
if(h.count(t)) h[t] = min(h[t], i);
else h[t] = i,vis[t] = 1;
t = (t*a) % p;
}
ex_gcd(t,p,x,y);
ll inv = x > 0 ? x % p : x % p + p;
for(ll i = 0; i < m; ++i) {
if(vis[b]) return i*m + h[b];
b = b * inv % p;
}
return -1;
}
int main(){
ll b,p,n;
while(~scanf("%lld%lld%lld",&p,&b,&n)){
if(n >= p){
puts("no solution");
continue;
}
ll ans = BSGS(b,n,p);
if(ans == -1) puts("no solution");
else printf("%lld\n",ans);
}
return 0;
}