from collections import * from itertools import * from functools import * from heapq import * import sys,math input = sys.stdin.readline mod = 10**8 + 9 P = [2,3,5,7,11,13,17,19,23,29,31] def answer(): seed,N,K,B = map(int,input().split()) X = [seed] for _ in range(N): seed = 1 + (seed**2 + seed*12345)%mod X.append(seed) Z = [] for p in P: while B%p==0: B //= p Z.append(p) C = Counter(Z) ans = 1<<60 for k,v in C.items(): Y = [] for x in X: y = x tmp = 0 while y%k==0: tmp += 1 y //= k Y.append(tmp) Y.sort() ans = min(ans,sum(Y[:K])//v) print(ans) for _ in range(int(input())): answer()