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