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