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