#line 1 "g.cpp" #pragma region Macros #include using namespace std; template inline bool chmax(T &a, T b) { if(a < b) { a = b; return 1; } return 0; } template inline bool chmin(T &a, T b) { if(a > b) { a = b; return 1; } return 0; } #ifdef DEBUG template ostream &operator<<(ostream &os, const pair &p) { os << '(' << p.first << ',' << p.second << ')'; return os; } template ostream &operator<<(ostream &os, const vector &v) { os << '{'; for(int i = 0; i < (int)v.size(); i++) { if(i) { os << ','; } os << v[i]; } os << '}'; return os; } void debugg() { cerr << endl; } template void debugg(const T &x, const Args &... args) { cerr << " " << x; debugg(args...); } #define debug(...) \ cerr << __LINE__ << " [" << #__VA_ARGS__ << "]: ", debugg(__VA_ARGS__) #define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl #else #define debug(...) (void(0)) #define dump(x) (void(0)) #endif struct Setup { Setup() { cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(15); } } __Setup; using ll = long long; #define ALL(v) (v).begin(), (v).end() #define RALL(v) (v).rbegin(), (v).rend() #define FOR(i, a, b) for(int i = (a); i < int(b); i++) #define REP(i, n) FOR(i, 0, n) const int INF = 1 << 30; const ll LLINF = 1LL << 60; constexpr int MOD = 998244353; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; void Case(int i) { cout << "Case #" << i << ": "; } int popcount(int x) { return __builtin_popcount(x); } ll popcount(ll x) { return __builtin_popcountll(x); } #pragma endregion Macros #line 1 "/home/siro53/kyo-pro/compro_library/math/pow_mod.hpp" ll pow_mod(ll n, ll k, ll mod) { if(k == 0) { return 1; } else if(k % 2 == 1) { return pow_mod(n, k - 1, mod) * n % mod; } else { ll t = pow_mod(n, k / 2, mod); return t * t % mod; } } #line 1 "/home/siro53/kyo-pro/compro_library/math/BSGS.hpp" // 与えられたx, y, pに対して、x^i=y(mod p)を満たす最小の正の整数iを返す // 存在しない場合は-1 // O(√p log(p)) ll modlog(ll x, ll y, ll p) { ll H = sqrt(p) + 1; pair baby[H]; for(ll b = 0, xby = y; b < H; b++, xby = (xby * x) % p) { baby[b] = make_pair(xby, b); } sort(baby, baby + H); ll xH = 1; for(int i = 0; i < H; ++i) { xH = (xH * x) % p; } for(ll a = 1, xaH = xH; a <= H; a++, xaH = (xaH * xH) % p) { auto it = lower_bound(baby, baby + H, make_pair(xaH + 1, 0LL)); if(it == baby) { continue; } it--; if(it->first == xaH) { return a * H - it->second; } } return -1; } #line 73 "g.cpp" int main() { ll A, B, P, Q; ll y = (Q - (P * pow_mod(A, MOD-2, MOD) % MOD) + MOD) % MOD; ll res = modlog(B, y, MOD); assert(res != -1); res += 2; cout << res << endl; }