#include <bits/stdc++.h>
using namespace std;
const int MAXT = 5e4 + 5;
long long k, t, cnt[21], size, csh, fact[20], out = 1, ans = 1;
void update() {
  memset(cnt, 0, sizeof cnt);
  size = 0;
  out = 1;
  ans = 1;
  csh = 0;
}
long long C(long long n, long long k) {
  if (k > n) {
    return 0;
  }
  long long ans = fact[n];
  ans /= fact[n - k];
  ans /= fact[k];
  return ans;
}
int main() {
  fact[0] = 1;
  for (int i = 1; i < 20; i++) {
    fact[i] = fact[i - 1] * i;
  }
  cin >> t;
  while (t--) {
    cin >> k;
    for (int i = 2; k != 0; i++) {
      cnt[k % i]++;
      k /= i;
      size++;
    }
    for (int i = size; i >= 1; i--) {
      out *= C(size - csh - i + 1, cnt[i]);
      csh += cnt[i];
    }
    csh = 0;
    size--;
    for (int i = size + 1; i >= 1; i--) {
      ans *= C(size - i - csh + 1, cnt[i]);
      csh += cnt[i];
    }
    if (!cnt[0]) {
      cout << out - 1 << endl;
      update();
      continue;
    }
    cout << out - ans - 1 << "\n";
    update();
  }
  return 0;
}
