#include <bits/stdc++.h>
using namespace std;
int n;
long long int x, y, t;
int main() {
  scanf("%d", &n);
  for (int e = 1; e <= n; e++) {
    t = 0;
    scanf("%lld %lld", &x, &y);
    while (x != 0) {
      if (x % y == 0) {
        x /= y;
        t++;
      } else {
        t += x % y;
        x = x - (x % y);
      }
    }
    printf("%lld\n", t);
  }
  return 0;
}
