#include <bits/stdc++.h>
using namespace std;
int T;
signed long long N, K;
signed long long non_self(signed long long seg, signed long long K) {
  if (seg == 0) return K * (K + 1) / 2;
  signed long long a = seg / K;
  signed long long b = seg % K;
  signed long long ns = non_self(a, K);
  signed long long s = a * (K * K + 1) + b * K + 1;
  signed long long t = a * (K * K + 1) + b * K + K;
  signed long long add = 0;
  if (t >= ns) add = min(K, t - ns + 1);
  signed long long ans =
      a * K * (K * K + 1) + b * K * K + K * (K + 1) / 2 + add;
  return ans;
}
signed long long hoge(signed long long N, signed long long K) {
  signed long long seg = (N - 1) / (K * K + 1);
  signed long long ns = non_self(seg, K);
  if (ns == N) return (K + 1) * (seg + 1);
  if (N > ns) N--;
  N--;
  N %= (K * K + 1);
  return seg * K * (K + 1) + N / K * (K + 1) + N % K + 1;
}
void solve() {
  int i, j, k, l, r, x, y;
  string s;
  cin >> T;
  while (T--) {
    cin >> N >> K;
    cout << hoge(N, K) << endl;
  }
}
int main(int argc, char** argv) {
  string s;
  int i;
  if (argc == 1) ios::sync_with_stdio(false), cin.tie(0);
  for (i = 0; i < (argc - 1); i++) s += argv[i + 1], s += '\n';
  for (i = 0; i < (s.size()); i++) ungetc(s[s.size() - 1 - i], stdin);
  cout.tie(0);
  solve();
  return 0;
}
