#include <bits/stdc++.h>
using namespace std;
const int maxt = 501;
long long p[maxt][maxt], cnt[maxt];
long long _V[maxt], _ret[maxt], _a[maxt], _b[maxt], _c[maxt];
int _T;
long long V, ret, a, b, c, a0, b0, c0;
int n, T;
void init() {
  scanf("%d", &n);
  V = 1;
  for (int i = 1; i <= n; i++) {
    scanf("%I64d%I64d", &p[i][1], &cnt[i]);
    p[i][0] = 1;
    for (int j = 2; j <= cnt[i]; j++) p[i][j] = p[i][j - 1] * p[i][1];
    V *= p[i][cnt[i]];
  }
}
void dfs2(long long B, int d) {
  if (a0 * B * B > V) return;
  if (d > n) {
    b0 = B;
    c0 = V / a0 / b0;
    if (a0 * b0 + a0 * c0 + b0 * c0 < ret)
      ret = a0 * b0 + a0 * c0 + b0 * c0, a = a0, b = b0, c = c0;
    return;
  }
  for (int t = cnt[d]; t >= 0; t--) dfs2(B * p[d][t], d + 1);
}
void dfs(long long A, int d) {
  if (A * A * A > V) return;
  if (d > n) {
    a0 = A;
    double tmp = sqrt(V / A);
    if (A * tmp * 2 + V / A <= ret) dfs2(1, 1);
    return;
  }
  int t = cnt[d];
  cnt[d] = 0;
  for (; t >= 0; t--, cnt[d]++) dfs(A * p[d][t], d + 1);
  cnt[d]--;
}
void work() {
  for (int i = 0; i < _T; i++)
    if (_V[i] == V) {
      ret = _ret[i];
      a = _a[i], b = _b[i], c = _c[i];
      return;
    }
  ret = V * 2 + 1;
  a = 1, b = 1, c = V;
  dfs(1, 1);
  ret *= 2;
  _ret[_T] = ret;
  _a[_T] = a, _b[_T] = b, _c[_T] = c;
  _V[_T++] = V;
}
void print() { printf("%I64d %I64d %I64d %I64d\n", ret, a, b, c); }
int main() {
  scanf("%d", &T);
  for (int i = 0; i < T; i++) {
    init();
    work();
    print();
  }
  return 0;
}
