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