#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  long long t, resp, n, k, temp;
  cin >> t;
  while (t--) {
    resp = 0;
    cin >> n >> k;
    while (n) {
      temp = n % k;
      resp += temp;
      n -= temp;
      n /= k;
      resp++;
    }
    cout << resp - 1 << endl;
  }
}
