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