#include <bits/stdc++.h>
using namespace std;
const int maxP = 15;
long long N1, C, curS, N;
long long p[maxP];
int A, B, s[maxP];
int t;
int pn;
int mdeg[maxP];
long long rS;
long long rA;
long long rB;
long long rC;
long double B1;
void go(int restx, int x, int i, int f) {
  if (i == pn || restx < p[i]) {
    if (f == 0) {
      A = x;
      N1 = N / A;
      B1 = sqrtl(N1);
      if (2 * B1 * A + N1 < rS) {
        for (int i = 0; i < pn; i++) {
          mdeg[i] -= s[i];
        }
        go(sqrt(N1) + 1, 1, 0, 1);
        for (int i = 0; i < pn; i++) {
          mdeg[i] += s[i];
        }
      }
    } else {
      B = x;
      C = N1 / B;
      curS = A * (B + C) + N1;
      if (curS < rS) {
        rS = curS;
        rA = A;
        rB = B;
        rC = C;
      }
    }
    return;
  }
  int m = 0, _restx[64], _x[64];
  while (restx >= 1 && m <= mdeg[i]) {
    _restx[m] = restx;
    _x[m++] = x;
    restx /= p[i];
    x *= p[i];
  }
  for (int j = m - 1; j >= 0; j--) {
    if (f == 0) s[i] = j;
    go(_restx[j], _x[j], i + 1, f);
  }
}
int main() {
  scanf("%d", &t);
  for (int l = t; l != 0; l--) {
    scanf("%d", &pn);
    for (int i = 0; i < pn; i++) {
      scanf("%lld %d", &p[i], &mdeg[i]);
    }
    N = 1;
    for (int i = 0; i < pn; i++) {
      for (int j = 0; j < mdeg[i]; j++) {
        N *= p[i];
      }
    }
    for (int i = 0; i < pn; i++) {
      for (int j = 0; j < pn - 1; j++) {
        if (p[j] > p[j + 1]) {
          swap(p[j], p[j + 1]);
          swap(mdeg[j], mdeg[j + 1]);
        }
      }
    }
    rS = 3 * N + 1;
    go(pow(N, 1.0 / 3) + 1, 1, 0, 0);
    printf("%lld %lld %lld %lld\n", 2 * rS, rA, rB, rC);
  }
  return 0;
}
