Here is my code :
#include<bits/stdc++.h>
#define ll long long
#define inf 1000000000
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen(“input.txt”,“r”, stdin);
freopen(“output.txt”,“w”, stdout);
#endif
ll t; cin >> t;
while(t--){
int n,k;
cin >> n >> k;
int ans = inf;
int occ = 0;
for(int i = 2; i*i <= k; i++) {
if(k%i == 0) {
occ = 0;
while(k%i == 0) {
occ++;
k = k/i;
}
int count = 0;
ll p = i;
while(p <= n) {
count += n/p;
p = p*i;
}
ans = min(ans,count/occ);
}
}
if(k > 1) {
ll p = k;
int count = 0;
while(p <= n) {
count += n/p;
p = p*k;
}
ans = min(ans,count);
}
if(ans == inf) {
ans = 0;
}
cout << ans << endl;
}
return 0;
}