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