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