题意:求最小的x使得满足 a ^ x % p = b % p, p是素数
思路:学习学习 Baby-Step-Gaint-Step 算法, 用map存还超时了, 还是用的散列表。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<iostream>
#include<algorithm>
typedef long long ll;
const int maxn = 1e5 + 10;
const ll INF = 1e18;
using namespace std;
ll qmod(ll x, ll n, ll mod) {
ll ans = 1;
while(n) {
if(n & 1) ans = ans * x % mod;
x = x * x % mod;
n >>= 1;
}
return ans;
}
ll exgcd(ll x, ll y) {
ll ansx = 1, ansy = 0, xi, now = y;
while(1) {
ll m = x % y, q = x / y;
if(!m) break;
xi = ansx - q * ansy;
x = y; y = m; ansx = ansy;
ansy = xi % now;
if(ansy < 0) ansy += now;
}
if(y != 1) return -1;
else return ansy;
}
map<ll, ll> hasha;
const ll hash_size = 131313;
ll hash_table[hash_size], mp[hash_size];
int main() {
ll p, a, b;
while(scanf("%lld %lld %lld", &p, &a, &b) != EOF) {
// hasha.clear();
memset(hash_table, -1, sizeof hash_table);
ll m = sqrt(p), ap = 1, dp = 1;
//hasha[1] = 0;
hash_table[1] = 1; mp[1] = 0;
for(ll i = 1; i < m; i++) {
ap = ap * a % p;
ll id = ap % hash_size;
while(hash_table[id] != -1 && hash_table[id] != ap) id = (id + 1) % hash_size;
if(hash_table[id] == -1) { hash_table[id] = ap; mp[id] = i; }
}
ap = ap * a % p;
int ans = -1;
for(ll i = 0; i <= m; i++) {
if(!i) dp = 1;
else dp = (dp * ap) % p;
ll inv = exgcd(dp, p);
//printf("d = %lld inv = %lld mod = %lld\n", dp, inv, p);
if(inv == -1) continue;
ll r = b * inv % p;
ll id = r % hash_size;
while(hash_table[id] != -1 && hash_table[id] != r) id = (id + 1) % hash_size;
if(hash_table[id] != -1) { ans = i * m + mp[id]; break; }
}
/*
if(hasha.count(b)) ans = hasha[b];
else {
for(ll i = 1; i <= m; i++) {
dp = dp * ap % p;
ll inv = exgcd(dp, p);
//printf("p = %lld dp = %lld dp-1 = %lld\n", p, dp, inv);
if(inv == -1) continue ;
ll r = (b * inv) % p;
if(hasha.count(r)) { ans = i * m + hasha[r]; break; }
}
}
*/
if(ans == -1) printf("no solution\n");
else printf("%d\n", ans);
}
return 0;
}