#include <bits/stdc++.h>
using namespace std;
int tt;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> tt;
  while (tt--) {
    long long n, k;
    cin >> n >> k;
    long long b = k * k + 1;
    function<long long(long long)> get = [&](long long cur) {
      if (!cur) {
        return k * (k + 1) / 2;
      }
      long long pos = get(cur / k);
      long long cnt = cur % k;
      long long l = (cur / k) * b + 1;
      l += cnt * k;
      long long r = l + k - 1;
      l += l >= pos;
      r += r >= pos;
      long long ans = -pos * ((r > pos) & (l < pos));
      ans += (r - l) * (r - l + 1) / 2 + l * (r - l + 1);
      return ans;
    };
    long long res = get((n - 1) / b);
    if (n == res)
      cout << (k + 1) * ((n - 1) / b + 1) << endl;
    else {
      long long x = n - (n > res) - (n - 1) / b;
      cout << x + ((x - 1) / k) << endl;
    }
  }
  return 0;
}
