#include using namespace std; #define rep(i,n) for(ll i=0;i=0;i--) #define perl(i,r,l) for(ll i=r-1;i>=l;i--) #define fi first #define se second #define pb push_back #define ins insert #define pqueue(x) priority_queue,greater> #define all(x) (x).begin(),(x).end() #define CST(x) cout<> #define rev(x) reverse(x); using ll=long long; using vl=vector; using vvl=vector>; using pl=pair; using vpl=vector; using vvpl=vector; const ll MOD=1000000007; const ll MOD9=998244353; const int inf=1e9+10; const ll INF=4e18; const ll dy[8]={1,0,-1,0,1,1,-1,-1}; const ll dx[8]={0,-1,0,1,1,-1,1,-1}; template inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; } template inline bool chmax(T& a, T b) { if (a <= b) { a = b; return true; } return false; } ll mod=100000009; ll prime[11]={2,3,5,7,11,13,17,19,23,29,31}; int main(){ ll q;cin >> q; while(q--){ ll seed,n,k,b;cin >> seed >> n >> k >> b; vl v(n+1);v[0]=seed; rep(i,n)v[i+1]=1+(v[i]*v[i]+v[i]*12345)%mod; vpl z; rep(i,11){ ll cnt=0; while(b%prime[i]==0){ cnt++;b/=prime[i]; } if(cnt)z.pb({prime[i],cnt}); } ll ans=inf; for(auto p:z){ vector num(n+1); rep(i,n+1){ while(v[i]%p.fi==0){ v[i]/=p.fi;num[i]++; } } //for(auto x:num)cout << x <<" " ;cout << endl; sort(all(num)); ll ret=0; rep(i,k)ret+=num[i]; ret/=p.se; chmin(ans,ret); } cout << ans <