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