#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
long long T, n, x, ans;
long long gi() {
  long long a = 0;
  char x = getchar();
  while (x < '0' || x > '9') x = getchar();
  while (x >= '0' && x <= '9')
    a = (a << 3) + (a << 1) + (x ^ 48), x = getchar();
  return a;
}
inline void solve(long long a, long long b) {
  if (a < b) swap(a, b);
  if (!b) return;
  ans += a / b * b * 3;
  solve(b, a % b);
}
int main() {
  T = gi();
  while (T--) {
    n = gi(), x = gi();
    ans = 0, solve(x, n - x);
    printf("%lld\n", ans);
  }
  return 0;
}
