#include <bits/stdc++.h>
using namespace std;
int l;
long long int f[99], v;
int e[99];
long long int x[999999];
int lx;
void dfs(int i, long long int now) {
  if (i == l) {
    x[lx++] = now;
    return;
  }
  for (int j = 0; j <= e[i]; j++) {
    dfs(i + 1, now);
    now *= f[i];
  }
}
map<long long int, pair<long long int, long long int> > Map;
int main() {
  int _;
  for (scanf("%d", &_); _--;) {
    scanf("%d", &l);
    v = 1;
    for (int i = 0; i < l; i++) {
      scanf("%I64d%d", &f[i], &e[i]);
      for (int j = 0; j < e[i]; j++) v *= f[i];
    }
    long long int o = -1, A, B, C;
    if (Map.count(v)) {
      A = Map[v].first;
      B = Map[v].second;
      C = v / A / B;
      o = A * B + B * C + C * A;
    } else {
      lx = 0;
      dfs(0, 1);
      sort(x, x + lx);
      int t = lower_bound(x, x + lx, (long long int)(pow(v + .5, 1. / 3))) - x;
      for (int i = t; i >= 0; i--) {
        long long int a = x[i], va = x[lx - i - 1],
                      u = (long long int)sqrt(va + .5);
        if (o != -1 && va + a * (u + u) >= o) break;
        long long int vada = va / a;
        for (int j = lower_bound(x, x + lx, u) - x; j < lx && x[j] <= vada;
             j++) {
          long long int c = x[j], b = va / c, now = a * (b + c) + va;
          if (o != -1 && now >= o) break;
          if (va == b * c) {
            o = now;
            A = min(min(a, b), c);
            C = max(max(a, b), c);
            B = a + b + c - A - C;
            break;
          }
        }
      }
    }
    printf("%I64d %I64d %I64d %I64d\n", o * 2, A, B, C);
    Map[v] = make_pair(A, B);
  }
  return 0;
}
