#include <bits/stdc++.h>
using namespace std;
long long mod = 1000000007;
int main() {
  cin.tie(0);
  cout.tie(0);
  ios_base::sync_with_stdio(0);
  long long n, k = 0, m, i, j = 0, a, l, g = 0;
  cin >> m;
  while (m--) {
    j = 0;
    cin >> n >> k;
    while (n) {
      j += n % k;
      n = n - n % k;
      if (n >= k) n /= k, j++;
      if (n < k) j += n, n = 0;
    }
    cout << j << endl;
  }
  return 0;
}
