#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n;
  long long k;
  long long i;
  long long count;
  int flag = 0;
  cin >> i;
  while (i--) {
    count = 0;
    cin >> n >> k;
    flag = 0;
    if (n == 0) {
      cout << "0" << endl;
      flag = 1;
    }
    while (n) {
      count = count + n % k + 1;
      n = n - n % k;
      n = n / k;
    }
    if (flag == 0) cout << count - 1 << endl;
  }
  return 0;
}
