#include <bits/stdc++.h>
using namespace std;
long long f[50];
long long foo(vector<long long> a) {
  long long s = 1;
  map<long long, long long> b;
  for (long long x : a) {
    b[x]++;
  }
  for (int i = 1; i <= a.size(); i++) {
    long long t = 0;
    for (long long x : a) {
      t += i >= x;
    }
    s *= max(0ll, t - i + 1);
  }
  for (auto i : b) {
    s /= f[i.second];
  }
  return s;
}
void solve() {
  long long k;
  cin >> k;
  vector<long long> a;
  long long n = 0;
  while (k) {
    n++;
    a.push_back(k % (n + 1));
    k /= n + 1;
  }
  sort(a.begin(), a.end());
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    if (a[i] == 0) continue;
    if (i == 0 || a[i] != a[i - 1]) {
      vector<long long> b;
      for (int j = 0; j < n; j++) {
        if (i != j) {
          b.push_back(a[j]);
        }
      }
      ans += foo(b);
    }
  }
  cout << ans - 1 << endl;
}
int main() {
  f[0] = 1;
  for (long long i = 1; i <= 40; i++) {
    f[i] = f[i - 1] * i;
  }
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
