#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
int main() {
  ios_base ::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  int T;
  cin >> T;
  while (T--) {
    long long n, k;
    cin >> n >> k;
    long long res = 0;
    while (n > 0) {
      res += n % k;
      n -= n % k;
      if (n == 0) break;
      res++;
      n /= k;
    }
    cout << res << '\n';
  }
  return 0;
}
