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