def solve(s,n,k,b): res = [0]*(n+1) for i in range(n+1): res[i] = s s = 1+(s*s+s*12345)%100000009 ans = 100000000 for p,t in fac[b]: val = [0]*(n+1) for i,si in enumerate(res): c = 0 while si%p==0: si //= p c += 1 val[i] = c val.sort() ans = min(ans,sum(val[:k])//t) return ans fac = [[] for _ in range(37)] for b in range(2,37): for p in [2,3,5,7,11,13,17,19,23,29,31]: c = 0 bb = b while bb%p==0: c += 1 bb //= p if c: fac[b].append((p,c)) Q = int(input()) for _ in range(Q): print(solve(*map(int,input().split())))