#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  vector<vector<long long> > c(31, vector<long long>(31, 0));
  c[0][0] = 1;
  for (int i = 1; i <= 30; i++) {
    c[i][0] = 1;
    for (int j = 1; j <= 30; j++) c[i][j] = c[i - 1][j] + c[i - 1][j - 1];
  }
  int t;
  cin >> t;
  while (t--) {
    long long k;
    cin >> k;
    vector<int> key;
    for (int i = 2; k; i++) {
      key.emplace_back(k % i);
      k /= i;
    }
    vector<int> num((int)key.size() + 1, 0);
    sort(key.begin(), key.end());
    for (auto i : key) num[i]++;
    auto cal = [&](int n) -> long long {
      if (n == 0) return 0;
      long long ans = 1;
      int placed = 0;
      for (int i = (int)key.size(); i; i--) {
        if (!num[i]) continue;
        if (n - placed - i + 1 < num[i]) return 0;
        ans *= c[n - placed - i + 1][num[i]];
        placed += num[i];
      }
      return ans;
    };
    long long res = cal((int)key.size());
    num[0]--;
    res -= cal((int)key.size() - 1);
    cout << res - 1 << '\n';
  }
  return 0;
}
