#include <bits/stdc++.h>
using namespace std;
struct ss {
  long long sur, x, y, z;
  ss() {}
  ss(long long a, long long b, long long c, long long d) {
    sur = a;
    x = b;
    y = c;
    z = d;
  }
} ans;
int n, tot, a[100], b[100];
long long x, uu, p[100], u[200000];
long long calc(long long a, long long b, long long c) {
  return a * b + a * c + b * c;
}
long long getsqr(long long a) {
  long long b = (long long)sqrt(a) + 1;
  while (b * b > a) --b;
  return b;
}
long long gettri(long long a) {
  long long b = (long long)pow(a, 1.0 / 3) + 1;
  while (b * b * b > a) --b;
  return b;
}
void dfs(int now, long long lim, long long xx) {
  if (!now) {
    u[++tot] = xx;
    return;
  }
  dfs(now - 1, lim, xx);
  for (int i = 1; i <= a[now]; ++i) {
    xx *= p[now];
    if (xx > lim) break;
    dfs(now - 1, lim, xx);
  }
}
void dfs2(int now, long long lim, long long xx) {
  if (!now) {
    if (calc(uu, xx, x / xx / uu) < ans.sur)
      ans = ss(calc(uu, xx, x / xx / uu), uu, xx, x / xx / uu);
    return;
  }
  dfs2(now - 1, lim, xx);
  for (int i = 1; i <= a[now]; ++i) {
    xx *= p[now];
    if (xx > lim) break;
    dfs2(now - 1, lim, xx);
  }
}
bool cmp(long long a, long long b) { return a > b; }
int main() {
  int T;
  cin >> T;
  for (int test = 1; test <= T; ++test) {
    cin >> n;
    x = 1;
    for (int i = 1; i <= n; ++i) {
      cin >> p[i] >> a[i];
      for (int j = 1; j <= a[i]; ++j) x *= p[i];
    }
    memcpy(b, a, sizeof(a));
    tot = 0;
    dfs(n, gettri(x), 1LL);
    sort(u + 1, u + tot + 1, cmp);
    ans = ss(calc(x, 1, 1), x, 1, 1);
    for (int i = 1; i <= tot; ++i) {
      long long vw = x / u[i], v = getsqr(vw), w = u[i];
      uu = u[i];
      if (calc(u[i], v, v) > ans.sur) continue;
      for (int j = 1; j <= n; ++j)
        while (w % p[j] == 0) {
          w /= p[j];
          --a[j];
        }
      dfs2(n, getsqr(vw), 1LL);
      memcpy(a, b, sizeof(b));
    }
    cout << ans.sur * 2 << " " << ans.x << " " << ans.y << " " << ans.z << endl;
  }
  return 0;
}
