#include <bits/stdc++.h>
inline char gc() {
  static char buf[10000], *p1 = buf, *p2 = buf;
  return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 10000, stdin), p1 == p2)
             ? EOF
             : *p1++;
}
inline long long read() {
  long long x = 0;
  int f = 1;
  char c = gc();
  for (; !isdigit(c); c = gc())
    if (c == '-') f = -1;
  for (; isdigit(c); c = gc()) x = (x << 1) + (x << 3) + (c ^ 48);
  return x * f;
}
inline void write(long long x) {
  if (x < 0) putchar('-'), x = -x;
  if (x > 9) write(x / 10);
  putchar(x % 10 | 48);
}
const int N = 1e3 + 10;
long long V, ans, A, B, C;
int n;
struct node {
  long long s;
  int num;
  inline bool operator<(const node& res) const { return s < res.s; }
} s[N];
inline long long pow(long long x, int y) {
  if (y == 1) return x;
  long long k = 1;
  for (; y; y >>= 1, x = x * x)
    if (y & 1) k = k * x;
  return k;
}
inline void dfs1(long long a, int x, long long b) {
  if (!x) {
    if (b < a) return;
    long long c = V / b / a;
    if (a * b + a * c + b * c < ans) {
      ans = a * b + a * c + b * c;
      A = a, B = b, C = c;
    }
    return;
  }
  for (int i = 0; i <= s[x].num; ++i) {
    if (a * b * 2 + b * b >= ans || a * b * b > V) return;
    dfs1(a, x - 1, b);
    if (i == s[x].num) break;
    b *= s[x].s;
  }
  return;
}
inline void dfs(int x, long long a) {
  if (x > n) {
    double tem = sqrt(V / a);
    if (tem * tem + a * tem * 2 >= ans) return;
    dfs1(a, n, 1);
    return;
  }
  for (register int i = 0; i <= s[x].num; ++i) {
    if (a * a * 3 >= ans || a * a * a > V) return;
    s[x].num -= i;
    dfs(x + 1, a);
    s[x].num += i;
    if (i == s[x].num) break;
    a *= s[x].s;
  }
  return;
}
int main() {
  for (register int T = read(); T; --T) {
    n = read();
    V = 1;
    for (register int i = 1; i <= n; ++i)
      s[i].s = read(), s[i].num = read(), V *= pow(s[i].s, s[i].num);
    std::sort(s + 1, s + 1 + n);
    ans = V << 1 | 1;
    A = B = 1, C = V;
    dfs(1, 1);
    write(ans << 1), putchar(' ');
    write(A), putchar(' ');
    write(B), putchar(' ');
    write(C), puts("");
  }
  return 0;
}
