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