#include <bits/stdc++.h>
using namespace std;
map<long long, long long> memo;
map<long long, int> memoA, memoB;
long long a[100], divisor[150000];
int p[100], tot;
void findDivisor(int i, int n, long long cur, int upper) {
  if (i == n) {
    divisor[tot++] = cur;
    return;
  }
  long long tmp = cur;
  for (int j = 0; j <= p[i]; j++) {
    findDivisor(i + 1, n, tmp, upper);
    if (j < p[i]) {
      tmp *= a[i];
      if (tmp > upper) break;
    }
  }
}
int main() {
  int T;
  scanf("%d", &T);
  while (T > 0) {
    T--;
    int n;
    scanf("%d", &n);
    long long V = 1;
    for (int i = 0; i < n; i++) {
      scanf("%I64d%d", &a[i], &p[i]);
      for (int j = 0; j < p[i]; j++) V *= a[i];
    }
    if (memo.count(V) > 0) {
      printf("%I64d %d %d %I64d\n", memo[V], memoA[V], memoB[V],
             V / memoA[V] / memoB[V]);
      continue;
    }
    tot = 0;
    findDivisor(0, n, 1, (int)ceil(sqrt(V)));
    sort(divisor, divisor + tot);
    long long ans = 4 * V + 2;
    int t1 = 1, t2 = 1;
    int upper1 = (int)ceil(pow((double)V, 1.0 / 3));
    for (int i = tot - 1; i >= 0; i--) {
      if (divisor[i] > upper1) continue;
      if (4 * sqrt((double)V * divisor[i]) > ans - 2 * V / divisor[i]) break;
      long long upper2 = (long long)ceil(sqrt((double)(V / divisor[i])));
      int tt = lower_bound(divisor, divisor + tot, upper2 + 1) - divisor;
      for (int j = tt - 1; j >= i; j--) {
        if (divisor[i] * divisor[j] + V / divisor[i] + V / divisor[j] > ans)
          break;
        if (V / divisor[i] % divisor[j] != 0) continue;
        long long tmp =
            divisor[i] * divisor[j] + V / divisor[i] + V / divisor[j];
        if (tmp * 2 < ans) {
          ans = tmp * 2;
          t1 = (int)divisor[i];
          t2 = (int)divisor[j];
        }
      }
    }
    memo[V] = ans;
    memoA[V] = t1;
    memoB[V] = t2;
    printf("%I64d %d %d %I64d\n", ans, t1, t2, V / t1 / t2);
  }
  return 0;
}
