#include <bits/stdc++.h>
using namespace std;
const int NN = 30;
vector<int> wanted;
int chk;
int n;
void get(long long x) {
  long long fix_x = x;
  int idx = 2;
  vector<int> ans;
  while (x > 0) {
    ans.push_back(x % idx);
    x /= idx;
    idx++;
  }
  vector<int> sorted = ans;
  sort(sorted.begin(), sorted.end());
  wanted = sorted;
}
int cnt[NN];
int ans;
bool used[NN];
void bkt(int x, int lst) {
  if (x == n) {
    ans++;
    return;
  }
  if (cnt[wanted[x]] == 0) {
    bkt(x + 1, 2);
  } else {
    for (int d = lst; d < n + 2; d++)
      if (used[d] == false) {
        if (d <= wanted[x]) continue;
        if (d == n + 1 && wanted[x] == 0) continue;
        used[d] = true;
        cnt[wanted[x]]--;
        bkt(x, d + 1);
        cnt[wanted[x]]++;
        used[d] = false;
      }
  }
}
int places[NN];
long long comb[NN][NN];
long long func(vector<int> dig, int N) {
  memset(cnt, 0, sizeof(cnt));
  for (int digit : dig) cnt[digit]++;
  sort(dig.begin(), dig.end());
  dig.resize(unique(dig.begin(), dig.end()) - dig.begin());
  memset(places, 0, sizeof(places));
  for (int i = 2; i < N; i++) {
    for (int digit : dig)
      if (i > digit) places[digit]++;
  }
  long long ans = 1;
  long long used = 0;
  for (int i = (int)dig.size() - 1; i >= 0; i--) {
    int digit = dig[i];
    ans *= comb[places[digit] - used][cnt[digit]];
    used += cnt[digit];
  }
  return ans;
}
int main() {
  for (int i = 0; i < NN; i++) comb[i][i] = comb[i][0] = 1;
  for (int i = 2; i < NN; i++) {
    for (int j = 1; j < i; j++)
      comb[i][j] = comb[i - 1][j] + comb[i - 1][j - 1];
  }
  int tests;
  scanf("%d", &tests);
  for (int t = 0; t < tests; t++) {
    long long x;
    scanf("%lld", &x);
    get(x);
    n = (int)wanted.size();
    long long ans = func(wanted, (int)wanted.size() + 2);
    if (cnt[0] > 0) {
      cnt[0]--;
      wanted.erase(wanted.begin());
      ans -= func(wanted, (int)wanted.size() + 2);
    }
    cout << ans - 1 << endl;
  }
  return 0;
}
