#include <bits/stdc++.h>
using namespace std;
const long long int inf = 1e9 + 7;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    long long int n, k;
    cin >> n >> k;
    if (k == 1) {
      cout << n;
      return 0;
    }
    long long int ct = 0;
    while (n != 0) {
      if (n % k == 0) {
        n /= k;
        ct++;
      } else {
        long long int tmp = n / k;
        ct += n - tmp * k;
        n = tmp * k;
      }
    }
    cout << ct << endl;
  }
}
