#include #include #include #include using namespace std; typedef long long ll; typedef atcoder::modint998244353 mint; vector pfact(int n){ vector ret; for (int i=2; i*i<=n; i++){ if (n % i == 0){ ret.push_back(i); while (n % i == 0){ n /= i; } } } if (n > 1) ret.push_back(n); return ret; } ll modpow(ll n, ll m, ll p){ ll ret = 1; ll tmp = n; while(m > 0){ if (m & 1){ ret *= tmp; ret %= p; } tmp *= tmp; tmp %= p; m >>= 1; } return ret; } bool is_p_root(int x, int p, vector &v){ for (int m: v){ if (modpow(x, (p-1)/m, p) == 1) return false; } return true; } int findpr(int p){ random_device seed_gen; mt19937 engine(seed_gen()); uniform_int_distribution dist(1, p-1); vector v = pfact(p-1); int x; do{ x = dist(engine); }while(!is_p_root(x, p, v)); return x; } int main(){ ll n; cin >> n; int p; cin >> p; ll mx = p-1; vector fact(mx + 1, 1); vector factinv(mx + 1, 1); fact[0] = 1; for (int i=1; i<=mx; i++){ fact[i] = fact[i-1] * i % p; } factinv[mx] = modpow(fact[mx], p-2, p); for (int i=mx; i>=1; i--){ factinv[i-1] = factinv[i] * i % p; } ll g = findpr(p); vector taio(p, -1); vector fuku(p-1, 0); { ll tmp = 1; for (int i=0; i a; while(n > 0){ a.push_back(n % p); n /= p; } reverse(a.begin(), a.end()); auto cmb = [&](ll n, ll r) -> ll { if (n < r) return 0; return fact[n] * factinv[r] % p * factinv[n-r] % p; }; vector dp(p-1); for (int num=0; num<(int)a.size(); num++){ vector ndp(p-1); vector g(p-1); for (int i=0; i<=a[num]; i++){ ll k = taio[cmb(a[num], i)]; assert(k != -1); g[k] += 1; } vector h = atcoder::convolution(g, dp); for (int i=0; i<(int)h.size(); i++){ ndp[i%(p-1)] += h[i]; } if (num > 0){ for (int i=1; i<=a[num]; i++){ ndp[taio[cmb(a[num], i)]] += 1; } } for (int i=(num<1); i