#include<stdio.h>
int main()
{
int N,m,n,sum;
scanf("%d",&N);
while(N--)
{
sum = 0;
scanf("%d%d",&m,&n);
while(m)
{
sum = sum + m/n;
m = m/n;
}
printf("%d\n",sum);
}
return 0;
}5