#include <bits/stdc++.h>
using namespace std;
int test, k, a[200], b[200], c[200], cnt, cnt1;
long long n, x, v, V, X, Y, second, ansa, ansb, ansc, q[200][200], Min, p[200];
map<long long, pair<pair<long long, long long>, pair<long long, long long> > >
    Mp;
inline void rec1(int pos, long long val) {
  if (pos == k + 1) {
    if (val + v / val < Min) {
      Min = val + v / val;
      X = val;
      Y = v / val;
    }
    return;
  }
  for (int i = 0; i <= c[pos]; ++i) {
    if (val * q[pos][i] <= V) rec1(pos + 1, val * q[pos][i]);
  }
}
inline void rec(int pos, long long val) {
  if (pos == k + 1) {
    v = n / val;
    double t = sqrt(v + 0.0);
    if (second + 1e-6 < v + 2 * val * t) return;
    V = (long long)(sqrt(v + 0.0) + 1e-5);
    for (int i = 1; i <= k; ++i) c[i] = a[i] - b[i];
    Min = 8 * (long long)(1e18);
    rec1(1, 1);
    if (v + val * (X + Y) < second) {
      second = v + val * (X + Y);
      ansa = X;
      ansb = Y;
      ansc = val;
    }
    return;
  }
  for (int i = 0; i <= a[pos]; ++i) {
    b[pos] = i;
    if (val * q[pos][i] <= x) rec(pos + 1, val * q[pos][i]);
  }
}
int main() {
  scanf("%d", &test);
  for (int it = 0; it < test; ++it) {
    scanf("%d", &k);
    second = 8 * (long long)(1e18);
    n = 1;
    cnt = 0;
    cnt1 = 0;
    for (int i = 1; i <= k; ++i) {
      scanf("%I64d%d", &p[i], &a[i]);
      q[i][0] = 1;
      for (int j = 1; j <= a[i]; ++j) {
        q[i][j] = q[i][j - 1] * p[i];
      }
      n *= q[i][a[i]];
    }
    if (Mp.count(n)) {
      printf("%I64d %I64d %I64d %I64d\n", Mp[n].first.first, Mp[n].first.second,
             Mp[n].second.first, Mp[n].second.second);
      continue;
    }
    x = (long long)(pow(n, 1.0 / 3) + 1e-5);
    rec(1, 1);
    Mp[n] = make_pair(make_pair(2 * second, ansa), make_pair(ansb, ansc));
    printf("%I64d %I64d %I64d %I64d\n", 2 * second, ansa, ansb, ansc);
  }
  return 0;
}
