#include <bits/stdc++.h>
#pragma warning(disable : 4996) ；
using namespace std;
const int N = 1e5 + 5;
long long n, t, k, a[N], sa[N], rk[N], sum1, sum2, cnt;
int main() {
  cin >> t;
  while (t--) {
    cnt = 0;
    cin >> n, cin >> k;
    while (n) {
      cnt += n % k;
      n /= k;
      cnt++;
    }
    cout << cnt - 1 << endl;
  }
  return 0;
}
