#include <bits/stdc++.h>
using namespace std;
void driver() {
  long long n, k;
  cin >> n >> k;
  long long count = 0;
  while (n != 0) {
    count += (n % k);
    n -= n % k;
    if (n) count += 1;
    n = n / k;
  }
  cout << count << '\n';
}
int main() {
  int t;
  cin >> t;
  while (t--) driver();
}
