#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ii = pair<int, int>;
int main() {
  ios::sync_with_stdio(0);
  int t;
  cin >> t;
  while (t--) {
    ll n, k;
    cin >> n >> k;
    ll ans = 0;
    while (n > 0) {
      if (n % k != 0) {
        ans += n % k;
        n -= n % k;
      } else
        ++ans, n /= k;
    }
    cout << ans << endl;
  }
}
