#include <bits/stdc++.h>
using namespace std;
long t;
long long k;
vector<long> a, b;
long long gt[21], dd[21];
long long tinh(vector<long> c) {
  memset(dd, 0, sizeof(dd));
  for (long i = 0; i < c.size(); i++) dd[c[i]]++;
  long long da = 1, sl = dd[0];
  for (long i = 0; i < c.size(); i++) {
    sl += dd[i + 1];
    da *= sl;
    sl--;
  }
  for (long i = 0; i <= 20; i++) da /= gt[dd[i]];
  return da;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  gt[0] = 1;
  for (long i = 1; i <= 20; i++) gt[i] = gt[i - 1] * i;
  cin >> t;
  while (t--) {
    cin >> k;
    a.clear();
    long sc = 1;
    while (k) {
      sc++;
      a.push_back(k % sc);
      k /= sc;
    }
    sort(a.begin(), a.end());
    long long kq = tinh(a);
    if (a[0] == 0) {
      b.clear();
      for (long i = 1; i < a.size(); i++) b.push_back(a[i]);
      kq -= tinh(b);
    }
    kq--;
    cout << kq << '\n';
  }
}
