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