#include <bits/stdc++.h>
const int N = 100012;
const int inf = (int)1e9;
const int maxn = 71;
using namespace std;
int d[maxn], m, Ta;
long long res, p[maxn][maxn], P[maxn], n, ra, rb, rc;
void solve(int i, long long a, long long b) {
  if (b * b > n / a) return;
  if (i == m) {
    long long c = n / a / b;
    if (res > 2 * a * b + 2 * a * c + 2 * b * c) {
      res = 2 * a * b + 2 * a * c + 2 * b * c;
      ra = a, rb = b, rc = c;
    }
    return;
  }
  for (int j = d[i]; j >= 0; j--) solve(i + 1, a, b * p[i][j]);
  return;
}
void dfs(int i, long long a) {
  if (a * a > n / a) return;
  if (i == m) {
    long long bc = n / a;
    if (sqrt(bc) * 2 * a + bc >= res / 2) return;
    solve(0, a, 1);
    return;
  }
  for (int j = d[i]; j >= 0; j--) d[i] -= j, dfs(i + 1, a * p[i][j]), d[i] += j;
  return;
}
int main() {
  for (scanf("%d", &Ta); Ta--;) {
    n = 1;
    scanf("%d", &m);
    for (int i = 0; i < m; i++) {
      scanf("%I64d%d", &P[i], &d[i]);
      p[i][0] = 1;
      for (int j = 1; j <= d[i]; j++) p[i][j] = p[i][j - 1] * P[i];
      n *= p[i][d[i]];
    }
    res = 4 * n + 2;
    ra = 1, rb = 1, rc = n;
    dfs(0, 1);
    printf("%I64d %I64d %I64d %I64d\n", res, ra, rb, rc);
  }
  return 0;
}
