import sys sys.setrecursionlimit(10**7) def I(): return int(sys.stdin.readline().rstrip()) def MI(): return map(int,sys.stdin.readline().rstrip().split()) def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) def LI2(): return list(map(int,sys.stdin.readline().rstrip())) def S(): return sys.stdin.readline().rstrip() def LS(): return list(sys.stdin.readline().rstrip().split()) def LS2(): return list(sys.stdin.readline().rstrip()) def prime_factorization(n): # nの素因数分解 res = {} for i in range(2,int(n**.5)+1): if n % i == 0: r = 0 # nがiで何回割り切れるか while n % i == 0: n //= i r += 1 res[i] = r if n != 1: res[n] = 1 return res Q = I() mod = 10**8+9 for _ in range(Q): s,N,K,B = MI() X = [s] for _ in range(N): x = X[-1] X.append(1+(x**2+x*12345) % mod) factorization = prime_factorization(B) prime_factor = list(factorization.keys()) d = {} for p in prime_factor: d[p] = [] for p in prime_factor: for i in range(N+1): x = X[i] r = 0 while x % p == 0: x //= p r += 1 d[p].append((r,i)) ans = 10**18 for p in prime_factor: d[p].sort() ans = min(ans,sum(d[p][i][0] for i in range(K))//factorization[p]) print(ans)