#include <bits/stdc++.h>
using namespace std;
const int Pr[25] = {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 int G[25] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
                   1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4};
const int Q[5] = {223092870, 58642669, 600662303, 33984931, 8633};
vector<int> f[5][20];
vector<int> Po;
int N, M, i, j, len, flag, Size, X, D, W, tmp, V;
char S[40];
int P[40], U[40];
long long A[10005];
long long C;
int Get(char ch) {
  if (ch == '?') return 0;
  if (ch >= '0' && ch <= '9') return ch - '0' + 1;
  if (ch >= 'A' && ch <= 'Z') return ch - 'A' + 11;
}
int get(char ch) {
  if (ch >= '0' && ch <= '9') return ch - '0';
  if (ch >= 'A' && ch <= 'Z') return ch - 'A' + 10;
}
void Specail(long long C) {
  int i;
  for (i = 0; i < 25; ++i)
    if (C % Pr[i] == 0) {
      printf("%d\n", Pr[i]);
      return;
    }
  printf("-1\n");
}
int dfs(int G, int D, int W, int V, int d) {
  int Sum = 1, i;
  if (f[G][D][W] != -1) return f[G][D][W];
  if (d == Size) {
    f[G][D][W] = A[V] % Q[G];
    return f[G][D][W];
  }
  for (i = 1; i <= D; ++i) {
    if (V + U[Po[d]] * (i - 1) >= N) break;
    Sum = (long long)Sum *
          dfs(G, D, W + P[Po[d]] * i, V + U[Po[d]] * (i - 1), d + 1) % Q[G];
  }
  f[G][D][W] = Sum;
  return Sum;
}
int main() {
  scanf("%d", &N);
  for (i = 0; i < N; ++i) scanf("%I64d", &A[i]);
  for (i = 0; i < 5; ++i)
    for (j = 2; j <= 16; ++j) {
      for (len = 0, X = 1; X <= N; ++len) X *= j;
      X = 1;
      for (; len--;) X *= (j + 1);
      f[i][j].resize(X + 1, -1);
    }
  scanf("%d", &M);
  for (i = 1; i <= M; ++i) {
    scanf("%d%s%I64d", &D, S, &C);
    len = strlen(S);
    for (j = 0; j < len; ++j) U[j] = P[j] = 0;
    U[len - 1] = 1;
    for (j = len - 2; j >= 0; --j) {
      if (U[j + 1] > N / D) break;
      U[j] = U[j + 1] * D;
    }
    flag = 0;
    for (j = 0; j < len; ++j)
      if (!U[j] && S[j] != '?' && S[j] != '0') flag = 1;
    P[len - 1] = 1;
    for (j = len - 2; j >= 0; --j) {
      if (!U[j]) break;
      P[j] = P[j + 1] * (D + 1);
    }
    if (flag) {
      Specail(C + 1);
      continue;
    }
    for (j = 0; j < len; ++j)
      if (!U[j]) S[j] = '0';
    Po.clear();
    for (j = 0; j < len; ++j)
      if (S[j] == '?') Po.push_back(j);
    Size = Po.size();
    W = 0;
    for (j = 0; j < len; ++j)
      if (U[j]) W = W * (D + 1) + Get(S[j]);
    V = 0;
    for (j = 0; j < len; ++j)
      if (U[j]) {
        V = V * D;
        if (S[j] != '?') V += get(S[j]);
      }
    if (V >= N) {
      Specail(C + 1);
      continue;
    }
    flag = 0;
    for (j = 0; j < 25; ++j) {
      tmp = dfs(G[j], D, W, V, 0);
      if ((tmp % Pr[j] + C % Pr[j]) % Pr[j] == 0) {
        printf("%d\n", Pr[j]);
        flag = 1;
        break;
      }
    }
    if (!flag) printf("-1\n");
  }
  return 0;
}
