#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n, k, ans = 0, t;
  cin >> t;
  while (t--) {
    cin >> n >> k;
    ans = 0;
    while (n > 0) {
      if (n % k == 0) {
        n /= k;
        ans++;
      } else {
        ans += n % k;
        n -= n % k;
      }
    }
    cout << ans << "\n";
  }
}
