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