#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
int t;
long long n;
vector<int> v;
long long cnt[30];
long long pos[30];
long long fact[21];
void init() {
  for (int i = 0; i < int(30); i++) cnt[i] = pos[i] = 0;
  v.clear();
}
int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(false);
  fact[0] = 1;
  for (int i = 1; i <= 20; i++) fact[i] = fact[i - 1] * i;
  cin >> t;
  while (t--) {
    init();
    long long n;
    cin >> n;
    int cur = 2;
    while (n) {
      v.push_back(n % cur);
      n /= cur;
      cur++;
    }
    sort(v.begin(), v.end());
    for (int i = 0; i < int(v.size()); i++) cnt[v[i]]++;
    pos[1] = cnt[0];
    for (int i = 2; i <= v.size() + 1; i++) pos[i] = pos[i - 1] + cnt[i - 1];
    long long A = 1;
    for (int i = 2; i <= v.size() + 1; i++) A *= (pos[i] - (i - 2));
    long long B = 1;
    if (cnt[0] == 0)
      B = 0;
    else {
      B = cnt[0];
      for (int i = 2; i <= v.size(); i++) B *= (pos[i] - (i - 1));
    }
    long long ans = A - B;
    for (int i = 0; i < int(21); i++) ans /= fact[cnt[i]];
    cout << ans - 1 << '\n';
  }
}
