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