#include <bits/stdc++.h>
using namespace std;
long long a[100][110000];
int len[100];
long long divisor[110000];
map<long long, vector<long long> > mp;
void merge(int x, int y, int z) {
  int i = 0, j = 0;
  len[z] = 0;
  while (i < len[x] || j < len[y]) {
    if (a[x][i] < a[y][j]) {
      a[z][len[z]] = a[x][i];
      i++;
      len[z]++;
    } else {
      a[z][len[z]] = a[y][j];
      j++;
      len[z]++;
    }
  }
  a[z][len[z]] = (1ll << 60);
}
int generate(int x, long long p, int c) {
  int y = x, i, j;
  vector<int> v;
  v.push_back(c);
  while (1) {
    int last = v[v.size() - 1];
    if (last == 0) {
      break;
    } else if (last % 2 == 1) {
      v.push_back(last / 2);
    } else {
      v.push_back(last - 1);
    }
  }
  for (i = v.size() - 2; i >= 0; i--) {
    int c1 = v[i + 1], c2 = v[i];
    if (c2 == 2 * c1 + 1) {
      long long q = 1;
      for ((j) = 0; (j) < (int)(c1 + 1); (j)++) q *= p;
      for ((j) = 0; (j) < (int)(len[y]); (j)++) a[y + 1][j] = a[y][j] * q;
      len[y + 1] = len[y];
      a[y + 1][len[y + 1]] = (1ll << 60);
      merge(y, y + 1, y + 2);
      y += 2;
    } else {
      for ((j) = 0; (j) < (int)(len[y]); (j)++) a[y][j] *= p;
      merge(x, y, y + 1);
      y++;
    }
  }
  return y;
}
void func(long long N, int D) {
  int i, j, k;
  long long ans = 4 * N + 2, x = 1, y = 1, z = N;
  j = D - 1;
  for ((i) = 0; (i) < (int)(D); (i)++) {
    long long N2 = N / divisor[i];
    while (N2 / divisor[j] / divisor[j] == 0) j--;
    for (k = j; k >= i; k--) {
      long long x2 = divisor[i], y2 = divisor[k];
      if (N2 % y2 != 0) continue;
      long long z2 = N2 / y2;
      long long ans2 = 2 * (x2 * y2 + y2 * z2 + z2 * x2);
      if (ans2 < ans) {
        ans = ans2;
        x = x2;
        y = y2;
        z = z2;
      }
      break;
    }
  }
  vector<long long> v;
  v.push_back(ans);
  v.push_back(x);
  v.push_back(y);
  v.push_back(z);
  mp[N] = v;
  cout << ans << ' ' << x << ' ' << y << ' ' << z << endl;
}
long long p[100];
int c[100];
int main(void) {
  int T, t, K, i, j;
  a[0][0] = 1;
  a[0][1] = (1ll << 60);
  len[0] = 1;
  cin >> T;
  for ((t) = 0; (t) < (int)(T); (t)++) {
    cin >> K;
    for ((i) = 0; (i) < (int)(K); (i)++) cin >> p[i] >> c[i];
    long long N = 1;
    for ((i) = 0; (i) < (int)(K); (i)++)
      for ((j) = 0; (j) < (int)(c[i]); (j)++) N *= p[i];
    if (mp.find(N) != mp.end()) {
      vector<long long> v = mp[N];
      cout << v[0] << ' ' << v[1] << ' ' << v[2] << ' ' << v[3] << endl;
      continue;
    }
    int x = 0;
    for ((i) = 0; (i) < (int)(K); (i)++) x = generate(x, p[i], c[i]);
    int D = len[x];
    for ((i) = 0; (i) < (int)(D); (i)++) divisor[i] = a[x][i];
    func(N, D);
  }
  return 0;
}
