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