#include <bits/stdc++.h>
using namespace std;
int t;
unsigned long long n, k, d, ans;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  cin >> t;
  while (t--) {
    ans = 0;
    cin >> n >> k;
    if (k > n) {
      cout << n << endl;
    } else {
      while (n) {
        while (n && n % k == 0) {
          n /= k;
          ans++;
        }
        if (n) {
          d = (n / k);
          ans += (n - (d * k));
          n = d * k;
        }
      }
      cout << ans << endl;
    }
  }
  return 0;
}
