#include <bits/stdc++.h>
using namespace std;
long long n, k;
long long T;
int main() {
  long long ans = 0;
  cin >> T;
  while (T--) {
    ans = 0;
    cin >> n >> k;
    while (n != 0) {
      ans += n % k;
      n /= k;
      if (n == 0) break;
      ans++;
    }
    printf("%lld\n", ans);
  }
}
