#include <bits/stdc++.h>
using namespace std;
const int K = 50;
long long p[K], Rem[K], V, As, Aa, Ac, Topc;
int q[K], k;
long long IN() {
  int c, f;
  long long x;
  while (!isdigit(c = getchar()) && c != '-')
    ;
  c == '-' ? (f = 1, x = 0) : (f = 0, x = c - '0');
  while (isdigit(c = getchar())) x = (x << 1) + (x << 3) + c - '0';
  return !f ? x : -x;
}
void DFS_C(long long a, int x, long long c) {
  if (c >= Topc) {
    long long S = V + a * (V / c + c);
    if (As == -1 || S < As) As = S, Aa = a, Ac = c;
    return;
  } else if (c * Rem[x] < Topc)
    return;
  if (x == k) return;
  for (int i = 0; i < q[x] + 1; i++) DFS_C(a, x + 1, c), c *= p[x];
}
void DFS_A(int x, long long a) {
  if (a > 1e6 || a * a * a > V) return;
  if (x == k) {
    if (As != -1 && V / a + a * 2 * sqrt(V / a) >= As) return;
    V /= a, Topc = sqrt(V);
    DFS_C(a, 0, 1), V *= a;
    return;
  }
  int pre = q[x];
  for (int i = 0; i < pre + 1; i++) DFS_A(x + 1, a), a *= p[x], q[x]--;
  q[x] = pre;
}
int main() {
  for (int T = IN(); T--;) {
    V = 1;
    As = -1;
    k = IN();
    for (int i = 0; i < k; i++) {
      p[i] = IN(), q[i] = IN();
      for (int j = 0; j < q[i]; j++) V *= p[i];
    }
    Rem[k] = 1;
    for (int i = k - 1; ~i; i--) {
      Rem[i] = Rem[i + 1];
      for (int j = 0; j < q[i]; j++) Rem[i] *= p[i];
    }
    DFS_A(0, 1);
    printf("%I64d %I64d %I64d %I64d\n", 2 * As, Aa, V / Aa / Ac, Ac);
  }
}
