# 素因数分解 import math def fac(x): L=int(math.sqrt(x)) FACT=dict() for i in range(2,L+2): while x%i==0: FACT[i]=FACT.get(i,0)+1 x=x//i if x!=1: FACT[x]=FACT.get(x,0)+1 return FACT def calc(NOW,B): A=0 while NOW%B==0: NOW//=B A+=1 return A Q=int(input()) for tests in range(Q): seed,N,K,B=map(int,input().split()) FAC=fac(B) NOW=seed X=[math.gcd(seed,B)] for i in range(N): NOW=1+(NOW*NOW+NOW*12345)%100000009 X.append(math.gcd(NOW,B)) ANS=1<<60 for f in FAC: X.sort(key=lambda x:calc(x,f)) AX=0 NOW=1 for j in range(K): NOW*=X[j] while NOW%B==0: NOW//=B AX+=1 ANS=min(ANS,AX) print(ANS)