#include #include #include template using MinHeap = std::priority_queue, std::greater>; struct Prime { int max_n; std::vector primes; std::vector isp; explicit Prime(int max_n) : max_n(max_n), isp(max_n + 1, true) { isp[0] = isp[1] = false; for (int i = 2; i * i <= max_n; ++i) { if (isp[i]) { for (int j = i; i * j <= max_n; ++j) { isp[i * j] = false; } } } for (int p = 2; p <= max_n; ++p) { if (isp[p]) primes.push_back(p); } } template bool isprime(T n) const { if (n <= max_n) return isp[n]; for (T p : primes) { if (p * p > n) break; if (n % p == 0) return false; } return true; } template std::vector> factorize(T n) const { std::vector> facts; for (T p : primes) { if (p * p > n) break; if (n % p != 0) continue; int exp = 0; while (n % p == 0) { n /= p; ++exp; } facts.emplace_back(p, exp); } if (n > 1) { facts.emplace_back(n, 1); } return facts; } template static std::vector divisors(T n) { std::vector ret; for (T p = 1; p * p <= n; ++p) { if (n % p != 0) continue; ret.push_back(p); if (n / p == p) continue; ret.push_back(n / p); } return ret; } }; const Prime P(100); using lint = long long; constexpr int INF = 1 << 30; lint next(lint x) { return (x * x + x * 12345) % 100000009 + 1; } lint dig(lint x, int b) { int ret = 0; while (x % b == 0) { x /= b; ++ret; } return ret; } void solve() { lint x; int n, k, b; std::cin >> x >> n >> k >> b; ++n; auto fs = P.factorize(b); int m = fs.size(); std::vector> heaps(m); while (n--) { for (int i = 0; i < m; ++i) { heaps[i].push(dig(x, fs[i].first)); } x = next(x); } int ans = INF; for (int i = 0; i < m; ++i) { int sum = 0; for (int j = 0; j < k; ++j) { sum += heaps[i].top(); heaps[i].pop(); } ans = std::min(ans, sum / fs[i].second); } std::cout << ans << "\n"; } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); int q; std::cin >> q; while (q--) solve(); return 0; }