#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1e6 + 7;
long long t, n, k, temp;
int main(int argc, char* argv[]) {
  cin >> t;
  while (t--) {
    cin >> n >> k;
    long long cnt = 0;
    while (n > 0) {
      if (n % k != 0) {
        cnt += n % k;
        n -= n % k;
      } else {
        cnt++;
        n /= k;
      }
    }
    cout << cnt << endl;
  }
  return 0;
}
