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