#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
template <class t>
inline void read(t &s) {
  s = 0;
  register int f = 1;
  register char c = getchar();
  while (!isdigit(c)) {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (isdigit(c)) s = (s << 3) + (s << 1) + (c ^ 48), c = getchar();
  s *= f;
  return;
}
inline void write(long long x) {
  if (x / 10) write(x / 10);
  putchar((x % 10) ^ '0');
  return;
}
long long dr[100][2];
long long sta[200050], top;
int n;
long long V, ans, A, B, C, sqrV, ta, sqrtV, limA;
long long mulV[100];
inline long long calc(long long x) {
  return 4ll * (long long)(ceil(sqrt(V) * sqrt(x))) + V / x * 2ll;
}
inline void dfs(int dep, long long mul) {
  if (mul > limA) return;
  if (dep > n) {
    sta[++top] = mul;
    return;
  }
  dfs(dep + 1, mul);
  for (int i = 1; i <= dr[dep][1]; ++i) mul *= dr[dep][0], dfs(dep + 1, mul);
  return;
}
inline void dfs2(int dep, long long mul) {
  if (mul * mulV[dep] < ta) return;
  if (dep > n) {
    register long long c = V / ta / mul;
    register long long t = 2ll * (ta * mul + mul * c + ta * c);
    if (t < ans) {
      ans = t;
      A = ta, B = mul, C = c;
    }
    return;
  }
  register int tt = dr[dep][1], Ta = ta;
  while (!(Ta % dr[dep][0])) Ta /= dr[dep][0], --dr[dep][1];
  register int Lim = dr[dep][1];
  for (int i = 1; i <= dr[dep][1]; ++i)
    if (mul * dr[dep][0] <= sqrV)
      mul *= dr[dep][0];
    else {
      Lim = i - 1;
      break;
    }
  while (Lim--) dfs2(dep + 1, mul), mul /= dr[dep][0];
  dfs2(dep + 1, mul);
  dr[dep][1] = tt;
  return;
}
inline void work() {
  top = 0;
  read(n);
  V = 1;
  for (int i = 1; i <= n; ++i) {
    read(dr[i][0]);
    read(dr[i][1]);
    for (int j = 1; j <= dr[i][1]; ++j) V *= dr[i][0];
  }
  mulV[n + 1] = 1;
  for (int i = n; i; --i) {
    mulV[i] = mulV[i + 1];
    for (int j = 1; j <= dr[i][1]; ++j) mulV[i] *= dr[i][0];
  }
  ans = 2ll * (2ll * V + 1);
  A = V, B = C = 1;
  limA = (long long)ceil(pow(V, 1.0 / 3.0));
  dfs(1, 1);
  sort(sta + 1, sta + top + 1);
  for (int i = top; i; --i)
    if (calc(sta[i]) < ans) {
      ta = sta[i];
      sqrV = (long long)ceil(sqrt(V) * sqrt(ta));
      dfs2(1, 1);
    }
  write(ans);
  putchar(' ');
  write(A);
  putchar(' ');
  write(B);
  putchar(' ');
  write(C);
  puts("");
  return;
}
signed main(void) {
  int t;
  cin >> t;
  while (t--) work();
  return 0;
}
