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