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