#include <bits/stdc++.h>
using namespace std;
const int INF = 0x7fffffff;
const int sINF = INF >> 2;
const long long LINF = 0x7fffffffffffffff;
const long long sLINF = LINF >> 2;
const int maxn = 1e5;
const int maxm = 1e5;
const int modn = 1e9 + 7;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long t, n, k;
  cin >> t;
  while (t--) {
    cin >> n >> k;
    long long ans(0);
    while (n) {
      if (n % k) {
        ans += n % k;
        n -= n % k;
      } else {
        ++ans;
        n /= k;
      }
    }
    cout << ans << endl;
  }
  return 0;
}
