#include <bits/stdc++.h>
const int mod = 1e9 + 7;
const int maxn = 1e7 + 10;
long long gcd(long long p, long long q) { return q == 0 ? p : gcd(q, p % q); }
using namespace std;
long long n, k;
int T;
int main() {
  ios::sync_with_stdio(false);
  cin >> T;
  while (T--) {
    cin >> n >> k;
    long long ans = 0, cnt = 0;
    while (n > 0) {
      ans += n % k;
      n /= k;
      ++cnt;
    }
    cout << ans + cnt - 1 << endl;
  }
  return 0;
}
