import bisect import copy import decimal import fractions import heapq import itertools import math import random import sys from collections import Counter, deque,defaultdict from functools import lru_cache,reduce from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max def _heappush_max(heap,item): heap.append(item) heapq._siftdown_max(heap, 0, len(heap)-1) def _heappushpop_max(heap, item): if heap and item < heap[0]: item, heap[0] = heap[0], item heapq._siftup_max(heap, 0) return item from math import gcd as GCD, modf read=sys.stdin.read readline=sys.stdin.readline readlines=sys.stdin.readlines Q=int(readline()) mod=10**8+9 primes=[2,3,5,7,11,13,17,19,23,29,31] for _ in range(Q): X,N,K,B=map(int,readline().split()) dct=defaultdict(int) for p in primes: if B%p==0: while B%p==0: B//=p dct[p]+=1 dct_lst=defaultdict(list) XX=X for p in dct: cnt=0 while XX%p==0: XX//=p cnt+=1 dct_lst[p].append(cnt) for _ in range(N): X=1+(X**2+X*12345)%mod XX=X for p in dct: cnt=0 while XX%p==0: XX//=p cnt+=1 dct_lst[p].append(cnt) for p in dct_lst: dct_lst[p].sort() ans=1<<60 for p in dct: ans=min(ans,sum(dct_lst[p][:K])//dct[p]) print(ans)