#include <bits/stdc++.h>
using namespace std;
const int maxn = 21;
long long C[maxn][maxn];
int T;
map<long long, int> vs;
void brute(int cur, vector<int> v) {
  int id[cur];
  for (int i = 0; i < cur; i++) id[i] = i;
  int cnt = 0;
  do {
    long long now = 0;
    int check = 1;
    for (int i = cur - 1; i >= 0; i--) {
      if (v[id[i]] > i + 1) {
        check = 0;
        break;
      }
      now = now * (i + 2) + v[id[i]];
    }
    if (!check) continue;
    if (!vs.count(now)) {
      for (int i = cur - 1; i >= 0; i--) {
        cout << v[id[i]] << ' ';
      }
      cout << endl;
      cout << now << '\n';
      cnt++;
    }
    vs[now] = 1;
  } while (next_permutation(id, id + cur));
  cout << cnt << endl;
}
int main() {
  for (int i = 0; i < maxn; i++) {
    C[i][0] = 1;
    for (int j = 1; j <= i; j++) {
      C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
    }
  }
  cin >> T;
  while (T--) {
    long long x;
    cin >> x;
    int cur = 2;
    vector<int> v;
    while (x) {
      v.push_back(x % cur);
      x /= cur;
      cur++;
    }
    cur--;
    sort(v.begin(), v.end());
    vector<pair<int, int>> a;
    for (int i = 0; i < ((int)v.size()); i++) {
      if (i && v[i] == v[i - 1]) {
        a[((int)a.size()) - 1].second++;
      } else {
        a.push_back(make_pair(v[i], 1));
      }
    }
    long long ans = 1;
    int tot = 0;
    for (int i = ((int)a.size()) - 1; i >= 0; i--) {
      int rem = cur - tot - max(a[i].first, 1);
      ans *= C[rem][a[i].second];
      tot += a[i].second;
    }
    if (a[0].first == 0) {
      a[0].second--;
      long long res = 1;
      tot = 0;
      for (int i = ((int)a.size()) - 1; i >= 0; i--) {
        int rem = cur - 1 - tot - max(a[i].first, 1);
        rem = max(rem, 0);
        res *= C[rem][a[i].second];
        tot += a[i].second;
      }
      ans -= res;
    }
    cout << ans - 1 << '\n';
  }
  return 0;
}
