#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
const int N = 1000005;
const double PI = 4 * atan(1);
const double eps = 1e-7;
long long t;
long long n, k;
long long res;
int main() {
  ios::sync_with_stdio(0);
  cin >> t;
  while (t--) {
    cin >> n >> k;
    res = 0;
    while (n != 0) {
      res += n % k;
      n = n - (n % k);
      while (n % k == 0 && n != 0) {
        res++;
        n /= k;
      }
    }
    cout << res << endl;
  }
  return 0;
}
