#include <bits/stdc++.h>
using namespace std;
const int pri[] = {2,  3,  5,  7,  11, 13, 17, 19, 23, 29, 31, 37, 41,
                   43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
const long long mo[5] = {223092870ll, 2756205443ll, 907383479ll, 42600829ll,
                         97ll};
int _pow(int a, int b, int mo) {
  int tmp = 1;
  a %= mo;
  for (; b; b >>= 1) {
    if (b & 1) tmp = (long long)tmp * a % mo;
    a = (long long)a * a % mo;
  }
  return tmp;
}
template <class T>
inline void R(T &xx) {
  xx = 0;
  char ch = getchar();
  bool F = 0;
  while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
  if (ch == '-') F = 1, ch = getchar();
  while (ch >= '0' && ch <= '9')
    xx = xx + xx + (xx << 3) + ch - 48, ch = getchar();
  if (F) xx = -xx;
}
long long a[100011], c, ans;
vector<long long> f[17][5];
int b[100], n, m, t, d;
char s[111];
int dp(int p) {
  int x = 0, y = 0;
  for (int i = 0; i < (int)t; i++) x = x * (d + 1) + b[i];
  if (~f[d][p][x]) return x;
  f[d][p][x] = 1;
  for (int i = 0; i < (int)t; i++)
    if (b[i] == d) {
      for (int j = 0; j < (int)d; j++)
        b[i] = j, (f[d][p][x] *= f[d][p][dp(p)]) %= mo[p];
      b[i] = d;
      return x;
    }
  for (int i = 0; i < (int)t; i++) y = y * d + b[i];
  if (y < n) f[d][p][x] = a[y] % mo[p];
  return x;
}
int main() {
  R(n);
  for (int i = 0; i < (int)n; i++) R(a[i]);
  for (int i = 2; i <= 16; i++) {
    int k = 1, l = 1;
    for (; k <= n; k *= i, l *= i + 1)
      ;
    for (int j = 0; j < (int)5; j++) f[i][j].resize(l, -1);
  }
  int _;
  for (R(_); _--;) {
    R(d);
    scanf("%s", s);
    R(c);
    t = 0;
    for (int j = 1; j <= n; j *= d, t++)
      ;
    for (int j = 0; j < (int)t; j++) {
      int k = strlen(s) - t + j;
      b[j] =
          k >= 0
              ? (s[k] == '?' ? d : (s[k] <= '9' ? s[k] - '0' : s[k] + 10 - 'A'))
              : 0;
    }
    int F = -1;
    for (int i = 0; i < (int)5; i++) {
      long long tmp = (f[d][i][dp(i)] + c) % mo[i];
      for (int j = 0; j < (int)25; j++)
        if (mo[i] % pri[j] == 0 && tmp % pri[j] == 0) {
          F = j;
          break;
        }
      if (~F) break;
    }
    printf("%d\n", (~F) ? pri[F] : -1);
  }
  return 0;
}
