#include <bits/stdc++.h>
using namespace std;
int t;
long long n, k, ilen;
long long get_special(long long inum) {
  if (inum == 0) return (k * (k + 1) / 2);
  long long prevint = inum / k;
  long long prevspec = get_special(prevint);
  long long t = inum % k;
  long long from = prevint * ilen + k * t + 1;
  long long to = prevint * ilen + k * (t + 1);
  long long offset = 0;
  if (from >= prevspec)
    offset = k;
  else if (to >= prevspec)
    offset = to - prevspec + 1;
  long long ret = from * k + k * (k - 1) / 2 + offset;
  return ret;
}
void solve() {
  cin >> n >> k;
  ilen = k * k + 1;
  long long inum = (n - 1) / ilen;
  long long spec = get_special(inum);
  if (n != spec) {
    long long pre_int = inum * (k * k + k);
    long long plus = n - inum * ilen - (n < spec ? 0 : 1);
    long long t = (plus - 1) / k;
    cout << pre_int + t + plus << endl;
    return;
  } else {
    long long homeint = inum / k;
    long long t = inum % k;
    long long pre_n = homeint * (k * k + k) + (k + 1) * (t + 1);
    cout << pre_n << endl;
    return;
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin >> t;
  while (t--) solve();
  return 0;
}
