#include <bits/stdc++.h>
using namespace std;
const int SIZE = 50;
const int CAP = 1e6;
long long p[SIZE];
int deg[SIZE];
long long divisors[CAP];
int divisors2[CAP];
int divisors3[CAP];
long long v;
int tempdiv[CAP];
map<long long, vector<long long> > mp;
int q;
long long getroot2(long long x) {
  long long l = 0, r = x + 1;
  while (l < r - 1) {
    long long mid = (l + r) / 2;
    bool bad = false;
    if (x / mid < mid)
      r = mid;
    else
      l = mid;
  }
  return l;
}
long long getroot3(long long x) {
  long long l = 0, r = x + 1;
  while (l < r - 1) {
    long long mid = (l + r) / 2;
    bool bad = false;
    if (x / mid < mid)
      r = mid;
    else if (x / mid < mid * mid)
      r = mid;
    else
      l = mid;
  }
  return l;
}
void checkall(long long &a, long long &b, long long &c) {
  int now = 0;
  divisors[now++] = 1;
  for (int i = 0; i < q; ++i) {
    int temp = now;
    long long current = p[i];
    for (int cnt = 1; cnt <= deg[i]; ++cnt, current *= p[i])
      for (int j = 0; j < temp; ++j) divisors[now++] = divisors[j] * current;
  }
  v = *max_element(divisors, divisors + now);
  if (mp.count(v)) {
    vector<long long> huh = mp[v];
    long long a = huh[0], b = huh[1], c = huh[2];
    return;
  }
  int root3 = getroot3(v);
  int root2 = getroot2(v);
  int cnt3 = 0;
  int cnt2 = 0;
  for (int i = 0; i < now; ++i)
    if (divisors[i] <= root3)
      divisors3[cnt3++] = divisors[i], divisors2[cnt2++] = divisors[i];
    else if (divisors[i] <= root2)
      divisors2[cnt2++] = divisors[i];
  long long curval = 2 * v + 1;
  a = 1;
  b = 1;
  c = v;
  sort(divisors3, divisors3 + cnt3);
  for (int i = cnt3 - 1; i >= 0; --i) {
    long long ta = divisors3[i];
    long long tempval = v / ta;
    if (curval <= tempval + 2 * sqrt(tempval) * ta) continue;
    for (int j = 0; j < cnt2; ++j) {
      long long tb = divisors2[j];
      if (tb < ta) continue;
      long long prod = (ta * tb);
      if (v % prod == 0) {
        long long tc = v / prod;
        long long sum = prod + tb * tc + tc * ta;
        if (sum < curval) {
          curval = sum;
          a = ta;
          b = tb;
          c = tc;
        }
      }
    }
  }
  mp[v] = {a, b, c};
}
int main() {
  ::ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  int test;
  cin >> test;
  while (test--) {
    cin >> q;
    long long amount = 1;
    for (int i = 0; i < q; ++i) cin >> p[i] >> deg[i], amount *= deg[i] + 1;
    long long a, b, c;
    checkall(a, b, c);
    cout << 2 * (a * b + b * c + c * a) << " " << a << " " << b << " " << c
         << endl;
  }
  return 0;
}
