#include <bits/stdc++.h>
using namespace std;
const int inf = 1000000000;
long long mod = 1000000007LL;
long long mod2 = 998244353LL;
int n, m;
int t;
long long k;
long long comb[21][21];
long long getres(int maxv, vector<int>& rs) {
  long long res = 1LL;
  int i = rs.size() - 1;
  while (i >= 0) {
    int j = i;
    while (j >= 0 && rs[j] == rs[i]) {
      j--;
    }
    int cnt = i - j;
    int cnt2 = maxv - rs[i];
    if (rs[i] == 0) cnt2--;
    cnt2 -= ((int)rs.size() - 1 - i);
    res = res * comb[cnt2][cnt];
    i = j;
  }
  return res;
}
int main() {
  cin >> t;
  for (int i = 0; i <= 20; ++i) {
    comb[i][0] = 1LL;
    for (int j = 1; j <= i; ++j) {
      comb[i][j] = (comb[i - 1][j - 1] + comb[i - 1][j]);
    }
  }
  for (int cas = 1; cas <= t; ++cas) {
    scanf("%lld", &k);
    vector<int> rs;
    rs.clear();
    int x = 2;
    while (k) {
      rs.push_back(k % x);
      k /= x;
      x++;
    }
    sort(rs.begin(), rs.end());
    int maxv = 2 + (int)rs.size() - 1;
    long long ans = getres(maxv, rs);
    if (rs[0] == 0) {
      maxv--;
      reverse(rs.begin(), rs.end());
      rs.pop_back();
      reverse(rs.begin(), rs.end());
      ans -= getres(maxv, rs);
    }
    printf("%lld\n", ans - 1);
  }
  return 0;
}
