#include <bits/stdc++.h>
#pragma GCC optimize(3)
using namespace std;
const double PI = acos((double)-1);
int ts, ts2;
int n, m;
long long p[50], a[50], mi[50][70], K, V = 1;
long long sur, aa, bb, cc;
double SQR, SQR2;
long long gcd(long long x, long long y) {
  long long t;
  for (; y != 0;) {
    t = x % y;
    x = y;
    y = t;
  }
  return x;
}
long long shen[50];
void DFS2(int k, long long la, long long x) {
  if (x > SQR2) return;
  if (k > K) {
    long long u1 = la * (x + V / la / x) + V / la;
    if (u1 < sur) sur = u1, aa = la, bb = x;
    return;
  }
  int i;
  for (i = shen[k]; i >= 0; i--) {
    DFS2(k + 1, la, x * mi[k][i]);
  }
}
void DFS(long long k, long long x) {
  if ((double)x * x * x - 1E-5 > V) return;
  if (k > K) {
    double u1 = sqrt((double)V / x), u2 = x * (u1 + u1) + u1 * u1;
    if (u2 >= sur) return;
    SQR2 = u1 + 1E-5;
    DFS2(1, x, 1);
    return;
  }
  int i;
  for (i = a[k]; i >= 0; i--) {
    shen[k] = a[k] - i;
    DFS(k + 1, x * mi[k][i]);
  }
}
int main() {
  long long i, j, k, t1, t2, t3, t4, t5, t, TES;
  double u1, u2, u3, u4, u5;
  char c1, c2, c3;
  srand((unsigned)time(0));
  cin >> TES;
  for (; TES; TES--) {
    cin >> K;
    V = 1;
    for (i = 1; i <= K; i++) {
      cin >> p[i] >> a[i];
    }
    for (i = 1; i <= K; i++) {
      t1 = 1;
      for (j = 1; j <= a[i]; j++) V *= p[i], t1 *= p[i], mi[i][j] = t1;
      mi[i][0] = 1;
    }
    t1 = (long long)sqrt(V);
    sur = 5000000000000000000ll;
    DFS(1, 1);
    cc = V / aa / bb;
    cout << sur * 2 << ' ' << aa << ' ' << bb << ' ' << cc << endl;
  }
  return 0;
}
