#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:36777216")
using namespace std;
const int N = 1e6 + 7;
const int INF = 0x3fffffff;
const int MOD = 1e9 + 7;
const double EPS = 1e-8;
int n, v[50], a[50];
long long V, aa, ra, rb, rc, tot, t[50][50], p[50];
long long calc(long long x, long long y, long long z) {
  return x * y + y * z + x * z;
}
void gao2(int pos, long long B) {
  if (V / aa / B / B < 1) return;
  if (pos == n + 1) {
    if (calc(aa, B, V / aa / B) < tot) {
      tot = calc(aa, B, V / aa / B);
      ra = aa, rb = B, rc = V / aa / B;
    }
    return;
  }
  for (int i = a[pos] - v[pos]; i >= 0; i--) {
    gao2(pos + 1, B * t[pos][i]);
  }
}
void gao(int pos, long long A) {
  if (V / A / A / A < 1) return;
  if (pos == n + 1) {
    long long k = sqrt(V / A + 0.5);
    if (2 * A * k + k * k - 5 <= tot) {
      aa = A;
      gao2(1, 1);
    }
    return;
  }
  for (int i = a[pos]; i >= 0; i--) {
    v[pos] = i;
    gao(pos + 1, A * t[pos][i]);
  }
}
int tt;
int main() {
  cin >> tt;
  while (tt--) {
    scanf("%d", &n);
    V = 1;
    for (int i = 1; i <= n; i++) {
      scanf("%I64d%d", &p[i], &a[i]);
      t[i][0] = 1;
      for (int j = 1; j <= a[i]; j++) t[i][j] = t[i][j - 1] * p[i], V *= p[i];
    }
    tot = 2 * (V + 1 + 1);
    gao(1, 1);
    printf("%I64d %I64d %I64d %I64d\n", 2 * tot, ra, rb, rc);
  }
}
