#include <bits/stdc++.h>
using namespace std;
uint64_t ans, fact[21];
long long t, n, cont, val;
bool us[30];
vector<uint64_t> v;
uint64_t calc() {
  uint64_t tmp = 1;
  uint64_t freq[30];
  uint64_t ind = 0;
  for (int i = 0; i < 30; i++) freq[i] = 0;
  for (int i = 0; i < v.size(); i++) {
    while (ind < v.size() && v[ind] < (i + 2)) {
      ind++;
    }
    freq[v[i]]++;
    tmp *= max((uint64_t)0, ind - i);
  }
  for (int i = 0; i < 30; i++) {
    tmp /= fact[freq[i]];
  }
  return tmp;
}
int main() {
  fact[0] = 1;
  for (int i = 1; i < 21; i++) fact[i] = fact[i - 1] * uint64_t(i);
  cin >> t;
  while (t--) {
    cin >> n;
    v.clear();
    ans = 0;
    memset(us, false, sizeof(us));
    cont = 2;
    while (n) {
      v.push_back(n % cont);
      n /= cont;
      cont++;
    }
    sort(v.begin(), v.end());
    for (int i = 0; i < v.size(); i++) {
      if (v[i] != 0 && us[v[i]] == false) {
        val = v[i];
        v.erase(v.begin() + i);
        ans += calc();
        v.insert(v.begin() + i, val);
        us[val] = true;
      }
    }
    cout << ans - 1 << "\n";
  }
  return 0;
}
