#!/usr/bin/ python3.8 import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines import numpy as np MOD = 100000009 Q = int(readline()) SNKB = np.array(read().split(), np.int64) S = SNKB[::4] N = SNKB[1::4] K = SNKB[2::4] B = SNKB[3::4] U = 10000 X = np.empty((Q, U + 1), np.uint64) X[:, 0] = S for n in range(1, U + 1): X[:, n] = (X[:, n - 1] * (X[:, n - 1] + 12345)) % MOD + 1 primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] def solve(X, N, K, B): X = X[:N + 1] def solve_p(p): nonlocal B e = 0 while B % p == 0: B //= p e += 1 A = np.zeros(len(X), np.int32) while True: q, r = np.divmod(X, p) if not np.count_nonzero(r == 0): break A[r == 0] += 1 X[r == 0] = q[r == 0] A.sort() return A[: K].sum() // e return min(solve_p(p) for p in primes if B % p == 0) for x, n, k, b in zip(X, N, K, B): print(solve(x, n, k, b))