#include <bits/stdc++.h>
using namespace std;
long long calc(vector<long long> v) {
  long long n = v.size(), i, j, k, ans = 1, ct;
  for (i = 0; i < n; i++) {
    if ((i == 0) || (v[i] != v[i - 1]))
      ct = 1;
    else
      ct++;
    ans *= max(0LL, n - max(0LL, v[i] - 1) - i);
    ans /= ct;
  }
  return ans;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long t, n, i, j, k, x, r, ans, ans2;
  cin >> t;
  while (t--) {
    cin >> x;
    vector<long long> v;
    for (i = 2; x > 0; i++) {
      v.push_back(x % i);
      x /= i;
    }
    sort(v.rbegin(), v.rend());
    ans = calc(v);
    if (v.back() == 0) {
      v.pop_back();
      ans2 = calc(v);
      ans -= ans2;
    }
    cout << ans - 1 << "\n";
  }
  return 0;
}
