#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    long long int n, k;
    cin >> n >> k;
    long long int ans = 0;
    if (n < k) {
      cout << n << endl;
      continue;
    }
    while (n != 0) {
      if (n % k == 0) {
        n = n / k;
        ans++;
      } else {
        long long x = n % k;
        n -= x;
        ans += x;
      }
    }
    cout << ans << endl;
  }
  return 0;
}
