#include <bits/stdc++.h>
using namespace std;
int t, k;
long long p[105];
int q[105];
long long V, ans, ansa, ansb, ansc, a, b, c;
long long MAXA, MAXB;
inline void bfs(int dep, long long sum) {
  if (sum > MAXB) return;
  if (dep > k) {
    if (sum < a) return;
    b = sum, c = V / a / b;
    if (a * b + b * c + a * c < ans)
      ans = a * b + b * c + a * c, ansa = a, ansb = b, ansc = c;
    return;
  }
  if (q[dep]) q[dep]--, bfs(dep, sum * p[dep]), q[dep]++;
  bfs(dep + 1, sum);
}
inline void dfs(int dep, long long sum) {
  if (sum > MAXA) return;
  if (dep > k) {
    a = sum;
    if (V / a + 2 * a * sqrt(V / a) < ans) MAXB = sqrt(V / a) + 1e-8, bfs(1, 1);
    return;
  }
  if (q[dep]) q[dep]--, dfs(dep, sum * p[dep]), q[dep]++;
  dfs(dep + 1, sum);
}
int main() {
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &k);
    V = 1;
    for (int i = 1; i <= k; ++i) {
      scanf("%lld%d", p + i, q + i);
      for (int j = 1; j <= q[i]; ++j) V *= 1ll * p[i];
    }
    MAXA = pow(V, 1.0 / 3) + 1e-8, ansa = ansb = ansc = 0,
    ans = 9223372036854775800;
    dfs(1, 1);
    printf("%lld %lld %lld %lld\n", 2 * ans, ansa, ansc, ansb);
  }
  return 0;
}
