#include <bits/stdc++.h>
using namespace std;
const int MAXN = 102;
int a[MAXN], ind;
long long solve() {
  long long ans = 1;
  vector<int> v;
  for (int i = 0; i < ind; i++) {
    int j = 1;
    while (i + 1 < ind && a[i] == a[i + 1]) {
      i++;
      j++;
      v.push_back(j);
    }
  }
  for (int i = ind - 1; i >= 0; i--) {
    ans *= (i + 1 - max(0, a[i] - 1));
    for (int i = 0; i < v.size(); i++)
      if (ans % v[i] == 0) {
        ans /= v[i];
        v[i] = 1;
      }
  }
  return ans;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    int i = 2;
    ind = 0;
    while (n) {
      a[ind++] = n % i;
      n /= i;
      i++;
    }
    sort(a, a + ind);
    long long ans = solve();
    if (a[0] == 0) {
      swap(a[0], a[ind - 1]);
      ind--;
      sort(a, a + ind);
      ans -= solve();
    }
    cout << ans - 1 << endl;
  }
  return 0;
}
