#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int t, n, k, i, sum = 0;
  cin >> t;
  for (i = 0; i < t; i++) {
    cin >> n >> k;
    if (k == 1) {
      cout << n << endl;
    } else {
      while (n >= k) {
        sum += n % k;
        n -= n % k;
        n = n / k;
        sum++;
      }
      sum += n % k;
      cout << sum << endl;
    }
    sum = 0;
  }
}
