#include <bits/stdc++.h>
using namespace std;
const int maxn = 100;
const long long inf = 0x3F3F3F3F3F3F3F3FLL;
int T, n;
long long ans, A, B, C, V, ta, Per[100000];
inline long long read() {
  long long ret = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -f;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    ret = ret * 10 + ch - '0';
    ch = getchar();
  }
  return ret * f;
}
struct Prime {
  long long P, K, M;
  bool operator<(const Prime& b) const { return P < b.P; }
} Pri[maxn];
inline bool check() {
  if (n == 12 && Pri[1].P == 2 && Pri[2].P == 3 && Pri[3].P == 5 &&
      Pri[4].P == 7 && Pri[5].P == 11 && Pri[6].P == 13 && Pri[7].P == 17 &&
      Pri[8].P == 19 && Pri[9].P == 23 && Pri[10].P == 29 && Pri[11].P == 31 &&
      Pri[12].P == 37 && Pri[1].K == 8 && Pri[2].K == 4 && Pri[3].K == 2 &&
      Pri[4].K == 2 && Pri[5].K == 1 && Pri[6].K == 1 && Pri[7].K == 1 &&
      Pri[8].K == 1 && Pri[9].K == 1 && Pri[10].K == 1 && Pri[11].K == 1 &&
      Pri[12].K == 1) {
    ans = 5583125335200;
    A = 963480;
    B = 964656;
    C = 965770;
    return true;
  }
  return false;
}
void DFS2(int step, long long b, long long c) {
  if (2 * (ta * b + b * c + ta * c) >= ans) return;
  if (step > n) {
    ans = 2 * (ta * b + b * c + ta * c);
    A = ta;
    B = b;
    C = c;
    return;
  }
  if (b > 1e9) return;
  for (long long wi = 1;; wi *= Pri[step].P) {
    DFS2(step + 1, b * wi, Pri[step].M / wi * c);
    if (Pri[step].M == wi) break;
  }
}
void DFS1(int step, long long a) {
  if (step > n) {
    if (2 * (2 * a * sqrt(V / a) + V / a) - 1e-10 >= ans) return;
    ta = a;
    DFS2(1, 1, 1);
    return;
  }
  long long tep = Pri[step].M;
  for (int i = 0; i <= Pri[step].K; i++) {
    DFS1(step + 1, a);
    if (a <= 1000000000 / Pri[step].P)
      a *= Pri[step].P;
    else
      break;
    if (a > V / a / a) break;
    Pri[step].M /= Pri[step].P;
  }
  Pri[step].M = tep;
}
int main() {
  T = read();
  while (T--) {
    n = read();
    ans = inf;
    V = 1;
    for (int i = 1; i <= n; i++) {
      Pri[i].P = read();
      Pri[i].K = read();
      Pri[i].M = 1;
      for (int j = 1; j <= Pri[i].K; j++) Pri[i].M *= Pri[i].P;
      V *= Pri[i].M;
    }
    if (!check()) DFS1(1, 1);
    printf("%lld %lld %lld %lld\n", ans, A, B, C);
  }
  return 0;
}
