from heapq import heappush,heappop Q=int(raw_input()) primes=[2,3,5,7,11,13,17,19,23,29] for i in range(Q): seed,N,K,B=map(int,raw_input().split()) ps=[] for p in primes: cnt=0 while B%p==0: cnt+=1 B/=p if cnt>0: ps.append((p,cnt)) hp = [[] for j in range(len(ps))] for j in range(N+1): x=seed #print x, for k in range(len(ps)): p=ps[k][0] cnt=0 while seed%p == 0: seed/=p cnt+=1 #print cnt, if len(hp[k]) < K: heappush(hp[k],-cnt) elif hp[k][0]<-cnt: heappop(hp[k]) heappush(hp[k],-cnt) #print seed=x*x seed%=100000009 seed+=x*12345 seed%=100000009 seed+=1 ans = 5000 for j in range(len(ps)): curAns = 0 for s in hp[j]: curAns-=s ans = min(ans,curAns/ps[j][1]) print ans