#include <bits/stdc++.h>
using namespace std;
const int N = 60;
long long a[60];
long long big[N];
int cnt[N], already;
long long limit, l;
long long lf;
long long i1, i2, i3;
struct item {
  long long res, a, b, c;
};
map<long long, item> base;
void gen2(int ps, int n, int cur, int top) {
  if (ps == n) {
    long long last = lf / cur;
    long long cc = last * cur + last * already + 1LL * already * cur;
    if (cc < limit) {
      limit = cc;
      i1 = last;
      i2 = cur;
      i3 = already;
    }
    return;
  }
  gen2(ps + 1, n, cur, top);
  int will = cur;
  for (int i = 1; i <= cnt[ps]; i++) {
    if (1LL * will * a[ps] > top) {
      break;
    }
    will *= a[ps];
    gen2(ps + 1, n, will, top);
  }
}
void gen1(int ps, int n, int cur, int top) {
  if (ps == n) {
    lf = l / cur;
    already = cur;
    int sq = sqrt(lf);
    if (1LL * sq * sq + 2LL * sq * cur >= limit) {
      return;
    }
    gen2(0, n, 1, sq + 1);
    return;
  }
  gen1(ps + 1, n, cur, top);
  int will = cur;
  for (int i = 1; i <= cnt[ps]; i++) {
    if (1LL * will * a[ps] > top) {
      break;
    }
    will *= a[ps];
    cnt[ps] -= i;
    gen1(ps + 1, n, will, top);
    cnt[ps] += i;
  }
}
void solve_test_case() {
  l = 1;
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i] >> cnt[i];
    for (int j = 0; j < cnt[i]; j++) {
      l *= a[i];
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 1; j < n; j++) {
      if (a[j - 1] > a[j]) {
        swap(a[j - 1], a[j]);
        swap(cnt[j - 1], cnt[j]);
      }
    }
  }
  if (base[l].res != 0) {
    cout << base[l].res << " " << base[l].a << " " << base[l].b << " "
         << base[l].c << "\n";
    return;
  }
  limit = (long long)8e18;
  gen1(0, n, 1, (int)pow(l, 1.0 / 3) + 1);
  limit *= 2;
  base[l].res = limit;
  base[l].a = i1;
  base[l].b = i2;
  base[l].c = i3;
  cout << limit << " " << i1 << " " << i2 << " " << i3 << "\n";
}
int main() {
  int tests;
  cin >> tests;
  for (int t = 0; t < tests; t++) {
    solve_test_case();
  }
}
