This documentation is automatically generated by online-judge-tools/verification-helper
#include "src/math/log_mod.hpp"
ll log_mod(ll a, ll b, ll mod)
$a^x \equiv b \pmod{\mathrm{mod}}$ を満たす非負整数 $x$ の最小値を返します.
存在しない場合は $-1$ を返します.
制約
計算量
#pragma once
#include "../template/template.hpp"
#include "../template/policy_based_data_structure.hpp"
long long log_mod(const long long a, long long b, const long long mod) {
assert(mod >= 1);
long long g = 1;
for(long long i = mod; i; i /= 2) (g *= a) %= mod;
g = gcd(g, mod);
long long t = 1, c = 0;
for(; t % g; ++c) {
if(t == b) return c;
(t *= a) %= mod;
}
if(b % g) return -1;
t /= g;
b /= g;
const long long n = mod / g;
long long h = 0, gs = 1;
for(; h * h < n; ++h) (gs *= a) %= n;
gp_hash_table<long long, long long> ht;
for(long long s = 0, e = b; s < h; ht[e] = ++s) {
(e *= a) %= n;
}
for(long long s = 0, e = t; s < n;) {
(e *= gs) %= n;
s += h;
if(ht.find(e) != ht.end()) return c + s - ht[e];
}
return -1;
}
#line 2 "src/template/template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<long long, long long>;
#define rep(i, a, b) for(long long i = (a); i < (b); ++i)
#define rrep(i, a, b) for(long long i = (a); i >= (b); --i)
constexpr long long inf = 4e18;
struct SetupIO {
SetupIO() {
ios::sync_with_stdio(0);
cin.tie(0);
cout << fixed << setprecision(30);
}
} setup_io;
#line 2 "src/template/policy_based_data_structure.hpp"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/tag_and_trait.hpp>
using namespace __gnu_pbds;
#line 4 "src/math/log_mod.hpp"
long long log_mod(const long long a, long long b, const long long mod) {
assert(mod >= 1);
long long g = 1;
for(long long i = mod; i; i /= 2) (g *= a) %= mod;
g = gcd(g, mod);
long long t = 1, c = 0;
for(; t % g; ++c) {
if(t == b) return c;
(t *= a) %= mod;
}
if(b % g) return -1;
t /= g;
b /= g;
const long long n = mod / g;
long long h = 0, gs = 1;
for(; h * h < n; ++h) (gs *= a) %= n;
gp_hash_table<long long, long long> ht;
for(long long s = 0, e = b; s < h; ht[e] = ++s) {
(e *= a) %= n;
}
for(long long s = 0, e = t; s < n;) {
(e *= gs) %= n;
s += h;
if(ht.find(e) != ht.end()) return c + s - ht[e];
}
return -1;
}