#include <bits/stdc++.h>
using namespace std;
long long sum(long long left, long long right) {
  if (right < left) {
    return 0;
  }
  return (right + left) * (right - left + 1) / 2;
}
long long get_nth_sum(long long n, long long k) {
  if (n == 0) {
    return k * (k + 1) / 2;
  }
  long long prev = n / k;
  long long id = n % k;
  long long cl = prev * (k * k + 1) + 1;
  long long cr = (prev + 1) * (k * k + 1);
  long long excluded = get_nth_sum(prev, k);
  long long rangel = cl + id * k;
  long long ranger = cl + (id + 1) * k - 1;
  if (excluded > ranger) {
    return sum(rangel, ranger);
  }
  if (excluded <= rangel) {
    return sum(rangel + 1, ranger + 1);
  }
  return sum(rangel, excluded - 1) + sum(excluded + 1, ranger + 1);
}
void solve() {
  long long n, k;
  cin >> n >> k;
  long long l = max(0LL, n / (k * k + 1) - 1), r = n / (k * k + 1) + 1;
  long long res = -1;
  while (l <= r) {
    long long key = (l + r) / 2;
    if (get_nth_sum(key, k) <= n) {
      res = key;
      l = key + 1;
    } else {
      r = key - 1;
    }
  }
  if (res != -1) {
    if (get_nth_sum(res, k) == n) {
      cout << (res + 1) * (k + 1) << endl;
      return;
    }
  }
  long long lft = n - (res + 1) * (k + 1);
  long long rowfullbefore = lft / k;
  if (lft % k == 0) {
    --rowfullbefore;
  }
  long long extra = rowfullbefore * (k + 1);
  if (lft % k == 0) {
    extra += k;
  } else {
    extra += lft % k;
  }
  cout << (res + 1) * (k + 1) + extra << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  for (int tt = 0; tt < t; ++tt) {
    solve();
  }
  return 0;
}
