#include <bits/stdc++.h>
using namespace std;
vector<int> dd;
long long fac[22] = {0};
long long calcaturec(int i, int j) { return fac[i] / fac[j] / fac[i - j]; }
long long cal(int n) {
  if (dd[n - 1]) return 0;
  for (int i = 0; i < n - 1; i++) {
    if (dd[i] >= n - i) return 0;
  }
  long long ret = 1;
  int x, y = 0;
  for (int i = 0; i < n; i++) {
    if (i) {
      if (dd[i] == dd[i - 1])
        y++;
      else {
        ret *= calcaturec(x, y);
        x = n - i - dd[i];
        y = 1;
      }
    } else {
      y++;
      x = n - i - dd[i];
    }
  }
  return ret;
}
int main() {
  fac[0] = 1;
  for (int i = 1; i <= 20; i++) fac[i] = fac[i - 1] * i;
  int t;
  long long d;
  scanf("%d", &t);
  while (t--) {
    dd.clear();
    scanf("%lld", &d);
    int num = 2;
    while (d) {
      dd.push_back(d % num);
      d /= num;
      num++;
    }
    sort(dd.begin(), dd.end());
    reverse(dd.begin(), dd.end());
    int n = dd.size();
    long long ans = 1;
    int x, y = 0;
    for (int i = 0; i < n; i++) {
      if (i) {
        if (dd[i] == dd[i - 1])
          y++;
        else {
          ans *= calcaturec(x + 1, y);
          x = n - i - dd[i];
          y = 1;
        }
      } else {
        y++;
        x = n - i - dd[i];
      }
    }
    ans -= cal(n);
    printf("%lld\n", ans - 1);
  }
  return 0;
}
