#include <bits/stdc++.h>
using namespace std;
long long fpm(long long b, long long e, long long m) {
  long long t = 1;
  for (; e; e >>= 1, b = b * b % m) e & 1 ? t = t * b % m : 0;
  return t;
}
template <class T>
inline bool chkmin(T &a, T b) {
  return a > b ? a = b, true : false;
}
template <class T>
inline bool chkmax(T &a, T b) {
  return a < b ? a = b, true : false;
}
template <class T>
inline T sqr(T x) {
  return x * x;
}
template <class edge>
struct Graph {
  vector<vector<edge>> adj;
  Graph(int n) {
    adj.clear();
    adj.resize(n + 5);
  }
  Graph() { adj.clear(); }
  void resize(int n) { adj.resize(n + 5); }
  void add(int s, edge e) { adj[s].push_back(e); }
  void del(int s, edge e) { adj[s].erase(find(iter(adj[s]), e)); }
  int deg(int v) { return adj[v].size(); }
  vector<edge> &operator[](int t) { return adj[t]; }
};
const int maxn = 30;
pair<long long, pair<long long, long long>> ans;
map<long long, pair<long long, pair<long long, long long>>> f;
int n;
long long a[maxn], p[maxn], V, A, B;
int lmtA, lmtB;
int cnt = 0, cnt2;
void dfs2(int B, int d) {
  if (d > n) {
    ++cnt;
    long long val = V + (B + V / B) * A;
    if (val < ans.first) ans = make_pair(val, make_pair(A, B));
    return;
  }
  int bak = a[d];
  for (; a[d] >= 0; --a[d]) {
    dfs2(B, d + 1);
    long long x = B * p[d];
    if (lmtB < x) break;
    B = x;
  }
  a[d] = bak;
}
void dfs(int A, int d) {
  if (d > n) {
    V /= A;
    lmtB = sqrt(V);
    if (V + A * (lmtB + V / lmtB) > ans.first) return (void)(V *= A);
    return (void)(::A = A, dfs2(1, 1), V *= A);
  }
  int bak = a[d];
  for (; a[d] >= 0; --a[d]) {
    dfs(A, d + 1);
    long long x = A * p[d];
    if (x > lmtA) break;
    A = x;
  }
  a[d] = bak;
}
int main() {
  ios_base::sync_with_stdio(false);
  int T;
  for (cin >> T; T--;) {
    cin >> n;
    V = 1;
    for (int i = 1; i <= n; ++i) {
      cin >> p[i] >> a[i];
      for (int j = 1; j <= a[i]; ++j) V *= p[i];
    }
    ({});
    lmtA = cbrt(V), ({});
    ans = make_pair(4e18, make_pair(0, 0));
    if (!f.count(V))
      dfs(1, 1), f[V] = ans;
    else
      ans = f[V];
    cout << ans.first * 2 << " " << ans.second.first << " " << ans.second.second
         << " " << V / ans.second.first / ans.second.second << endl;
  }
  ({}), ({});
  cerr << 1.0 * clock() / CLOCKS_PER_SEC << endl;
  return 0;
}
