#include <bits/stdc++.h>
using namespace std;
const int Max = 1e6 + 5;
int lst[Max];
int main() {
  int t;
  cin >> t;
  while (t--) {
    long long n, k;
    cin >> n >> k;
    long long sum = 0;
    while (n > 0) {
      if (n % k == 0) {
        n /= k;
        sum++;
      } else {
        sum += n % k;
        n -= n % k;
      }
    }
    cout << sum << endl;
  }
}
