#include using namespace std; using ll = long long; const int MOD = 100000009; vector> prime_factorize(int n) { vector> ret; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int num = 0; while (n % i == 0) { num++; n /= i; } ret.push_back({i, num}); } } if (n != 1) ret.push_back({n, 1}); return ret; } int main() { int Q; cin >> Q; while (Q--) { ll seed, N, K, B; cin >> seed >> N >> K >> B; vector X(N + 1); X[0] = seed; for (int i = 1; i <= N; i++) { X[i] = 1 + ((X[i - 1] * X[i - 1] + X[i - 1] * 12345) % MOD); } int ans = 1e9; auto pf = prime_factorize(B); for (auto& p : pf) { vector cnt(N + 1); int prime = p.first; for (int i = 0; i <= N; i++) { int n = 0; int tmp = prime; while (X[i] && X[i] % tmp == 0) { tmp *= prime; n++; } cnt[i] = n; } sort(cnt.begin(), cnt.end()); int sum = 0; for (int i = 0; i < K; i++) { sum += cnt[i]; } ans = min(ans, sum / p.second); } cout << ans << endl; } }