#include #include #include #include using namespace std; const int MOD = (int)1e8 + 9; const int INF = (int)1e9 + 7; using ll = long long; map prime_factorize(long long n) { map res; for (long long p = 2; p * p <= n; ++p) { while (n % p == 0) { ++res[p]; n /= p; } } if (n != 1) res[n] = 1; return res; } int main() { int Q; cin >> Q; while (Q--) { ll seed, N, K, B; cin >> seed >> N >> K >> B; vector X(N + 1, 0); X[0] = seed; for (int i = 1; i <= N; i++) { X[i] = 1LL + (X[i - 1] * X[i - 1] + X[i - 1] * 12345) % MOD; } int mi = INF; for (auto &p: prime_factorize(B)) { vector cnt(N + 1); for (int i = 0; i <= N; i++) { int c = 0; while (X[i] % p.first == 0) X[i] /= p.first, c++; cnt[i] = c; } sort(cnt.begin(), cnt.end()); int sum = 0; for (int i = 0; i < K; i++) sum += cnt[i]; mi = min(mi, sum / p.second); } cout << mi << endl; } return 0; }