import math def isprime(a): b = int(math.sqrt(a)) for i in range(2, b): if a % i == 0: return False return True Q = int(input()) for i in range(Q): seed, N, K, B = map(int, input().split()) N += 1 X = [] X.append(seed) for j in range(N): X.append(1 + (X[j] * X[j] + X[j] * 12345) % 100000009) ans = 99999999 for j in range(2, B + 1): if not isprime(j): continue if B % j != 0: continue div = 0 tmpB = B while(B % j == 0): B = B // j div += 1 ar = [0] * N for k in range(N): tmp = X[k] while tmp % j == 0: ar[k] += 1 tmp = tmp // j ar.sort() mul = 0 for k in range(K): mul += ar[k] ans = min(ans, mul // div) print(ans)