#include <bits/stdc++.h>
using namespace std;
inline long long start_diff(long long k) { return 1ll * k * (k - 1) / 2; }
long long get_inner_diff(pair<int, int> bucket, long long pos, long long k) {
  long long cnt, add;
  tie(cnt, add) = bucket;
  if (pos <= cnt) {
    return -pos;
  } else if (pos == cnt + 1) {
    return add - pos;
  } else {
    return k - pos;
  }
}
pair<long long, long long> gen_bucket(long long bid, long long k) {
  long long diff = start_diff(k);
  if (bid > 0) {
    auto bpar = gen_bucket(bid / k, k);
    diff += get_inner_diff(bpar, bid % k, k);
  }
  long long cnt = (diff - 1) / k;
  diff -= 1ll * cnt * k;
  return make_pair(cnt, k - (diff - 1));
}
long long solve(long long n, long long k) {
  if (n <= k) return n;
  long long blen = (1ll * k * k + 1) * k;
  long long bid = (n - k - 1) / blen, bpos = (n - k - 1) % blen;
  long long cnt, add;
  auto bucket = gen_bucket(bid, k);
  tie(cnt, add) = bucket;
  long long len = 1ll * k * k + 1;
  long long pos = bpos / len, spos = bpos % len;
  long long bad_pos = start_diff(k) - 1 + get_inner_diff(bucket, pos, k);
  if (spos == bad_pos) {
    long long gen_n = (n - 1ll * k * (k - 1) / 2) / k;
    return solve(gen_n, k) + k;
  } else {
    long long ans = n;
    ans -= bid * k + pos;
    if (spos > bad_pos) {
      ans--;
    }
    ans += 1 + bid * k * k + 1ll * k * pos;
    if (spos > bad_pos) {
      ans += (spos - 1) / k;
    } else {
      ans += spos / k;
    }
    return ans;
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  int t;
  cin >> t;
  for (int i = 0; i < t; ++i) {
    long long n, k;
    cin >> n >> k;
    cout << solve(n, k) << '\n';
  }
  return 0;
}
