#include <bits/stdc++.h>
using namespace std;
const int N = 100;
const double eps = 1e-9;
const int oo = 1000000000;
int n, b[N];
long long a[N], S, q[N][N], aa, ab, ac, p, x, y, z;
void dfs(int t, int u, long long x, long long y) {
  if (t == 2) {
    z = p / y;
    if (S >= 2 * (x * y + y * z + z * x)) {
      S = 2 * (x * y + y * z + z * x);
      aa = x;
      ab = y;
      ac = z;
    }
  } else if (t == 0) {
    if (x * x > p / x) {
      return;
    }
    if (u == n) {
      p /= x;
      if (4 * x * sqrt(p) + 2 * p < S) {
        dfs(t + 1, 0, x, y);
      }
      p *= x;
      return;
    }
    for (int i = b[u]; i >= 0; --i) {
      b[u] -= i;
      dfs(t, u + 1, x * q[u][i], y);
      b[u] += i;
    }
  } else {
    if (y * y > p) {
      return;
    }
    if (u == n) {
      dfs(t + 1, 0, x, y);
      return;
    }
    for (int i = b[u]; i >= 0; --i) {
      dfs(t, u + 1, x, y * q[u][i]);
    }
  }
}
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    scanf("%d", &n);
    p = aa = ab = ac = 1;
    for (int i = 0; i < n; ++i) {
      char iformat1[] = "%lld%lld";
      char iformat2[] = "%I64d%I64d";
      scanf(iformat2, &a[i], &b[i]);
      q[i][0] = 1;
      for (int j = 1; j <= b[i]; ++j) {
        ac *= a[i];
        q[i][j] = q[i][j - 1] * a[i];
        p *= a[i];
      }
    }
    S = 2 * (aa * ab + aa * ac + ab * ac);
    dfs(0, 0, 1, 1);
    char format1[] = "%lld %lld %lld %lld\n";
    char format2[] = "%I64d %I64d %I64d %I64d\n";
    printf(format2, S, aa, ab, ac);
  }
  return 0;
}
