#include <bits/stdc++.h>
using namespace std;
int main() {
  int ttt;
  scanf("%d", &ttt);
  while (ttt--) {
    long long n, k;
    scanf("%lld %lld", &n, &k);
    long long cnt = 0;
    while (n) {
      if (n % k == 0)
        n /= k, cnt++;
      else
        cnt += n % k, n -= n % k;
    }
    printf("%lld\n", cnt);
  }
  return 0;
}
