#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; using vi = vector; using vvi = vector; using vl = vector; using vvl = vector; using vb = vector; using vvb = vector; using vd = vector; using vs = vector; using pii = pair; using pll = pair; using pdd = pair; using vpii = vector; using vpll = vector; using vpdd = vector; const int inf = (1 << 30) - 1; const ll INF = 1LL << 60; //const int MOD = 1000000007; const int MOD = 998244353; vector prime_factorize(ll N) { vector res; for (ll a = 2; a * a <= N; ++a) { if (N % a != 0) continue; ll ex = 0; while (N % a == 0) { ++ex; N /= a; } res.push_back({ a, ex }); } if (N != 1) res.push_back({ N, 1 }); return res; } template ostream& operator <<(ostream& s, pair P) { return s << P.first << " " << P.second; } int main() { int q; cin >> q; int mod = 100000009; while (q--) { int seed, n, k, b; cin >> seed >> n >> k >> b; vl x(n + 1); x[0] = seed; for (int i = 0; i < n; i++) { x[i + 1] = 1 + (x[i] * x[i] + 12345 * x[i]) % mod; } // Bの素因数が一組揃うとB進数で0になる // 例として、B=12(2^2*3^1)の時、Tの素因数について // min(2の数/2, 3の数) が答えになるので、 // それぞれの素因数について、Xの小さい方からK個分 // 選んだ時の最小値を探す vpii pb = prime_factorize(b); int ans = inf; for (auto [p, num] : pb) { vi cnt(n + 1, 0); for (int i = 0; i <= n; i++) { int tmp = x[i]; while (x[i] % p == 0) { x[i] /= p; cnt[i]++; } } sort(cnt.begin(), cnt.end()); int sum = 0; for (int i = 0; i < k; i++) { sum += cnt[i]; } ans = min(ans, (int)(sum / num)); } cout << ans << endl; } return 0; }