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