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