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