#include <bits/stdc++.h>
using namespace std;
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  long long n, k, t, l = 0;
  cin >> t;
  while (t--) {
    l = 0;
    cin >> n >> k;
    while (n != 0) {
      if (n % k == 0) {
        l++;
        n = n / k;
      } else {
        l = l + n % k;
        n -= n % k;
      }
    }
    cout << l << "\n";
  }
  return 0;
}
