INF = 2 ** 25 MOD = 100000009 def gen(seed, N): x = [0] * (N + 1) x[0] = seed for n in range(1, N + 1): pre = x[n - 1] x[n] = 1 + (pre * pre % MOD + pre * 12345) % MOD return x def getFactors(n): res = [] p = 2 while p * p <= n: if n % p == 0: e = 0 while n % p == 0: e += 1 n //= p res.append((p, e)) p += 1 if n != 1: res.append((n, 1)) return res def solve(seed, N, K, B): x = gen(seed, N) factors = getFactors(B) res = INF for i in range(len(factors)): p, e = factors[i] y = x[:] for j in range(len(y)): num = y[j] cnt = 0 while num % p == 0: cnt += 1 num //= p y[j] = cnt y.sort() sum_ = sum(y[:K]) res = min(res, sum_ // e) return res if __name__ == '__main__': Q = int(input()) for i in range(Q): seed, N, K, B = map(int, input().split()) print(solve(seed, N, K, B))