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