#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    long long n, k;
    scanf("%I64d %I64d", &n, &k);
    long long ans = 0;
    while (n) {
      if (n % k == 0) {
        ans++, n /= k;
        continue;
      }
      long long r = n / k;
      ans += n % k;
      n = k * r;
    }
    cout << ans << endl;
  }
  return 0;
}
