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