mod = 10**8+9 def solve(): seed,n,k,b = map(int,input().split()) l = [] p = [] for i in range(2,b+1): if b%i: continue l.append(i) c = 0 while b%i == 0: b //= i c += 1 p.append(c) lis = [[] for i in range(len(l))] for i in range(n+1): now = seed for j,m in enumerate(l): c = 0 while now%m == 0: now //= m c += 1 lis[j].append(c) seed = 1 + (seed*(seed+12345))%mod ans = 10**10 for i,l in enumerate(lis): l.sort() s = sum(l[:k]) ans = min(ans,s//p[i]) return ans Q = int(input()) for i in range(Q): print(solve())