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