#include <bits/stdc++.h>
using namespace std;
const int pri[26] = {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, -1};
const long long mo[5] = {223092870ll, 2756205443ll, 907383479ll, 42600829ll,
                         97ll};
long long a[10000], c, ans;
vector<long long> f[17][5];
int b[100], n, m, t, d, k, l;
char s[40];
void prework() {
  int j = 0;
  for (int i = 2; i <= 16; i++) {
    for (j = 0, k = l = 1; k <= n; k *= i, l *= i + 1)
      ;
    for (j = 0; j < 5; j++) f[i][j].resize(l, -1);
  }
}
int calc(int d, int p) {
  int x = 0, y = 0;
  for (int i = 0; i < t; i++) x = x * (d + 1) + b[i];
  if (f[d][p][x] != -1) return x;
  f[d][p][x] = 1;
  for (int i = 0; i < t; i++)
    if (b[i] == d) {
      for (int j = 0; j < d; j++) {
        b[i] = j;
        f[d][p][x] = f[d][p][x] * f[d][p][calc(d, p)] % mo[p];
      }
      b[i] = d;
      return x;
    }
  for (int i = 0; i < t; i++) y = y * d + b[i];
  if (y < n) f[d][p][x] = a[y] % mo[p];
  return x;
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%I64d", &a[i]);
  prework();
  scanf("%d", &m);
  int flag;
  while (m--) {
    scanf("%d", &d);
    scanf("%s", s);
    scanf("%I64d", &c);
    t = 0;
    for (int j = 1; j <= n; t++, j *= d)
      ;
    for (int j = 0; j < t; j++) {
      k = strlen(s) - t + j;
      b[j] =
          k >= 0
              ? (s[k] == '?' ? d : (s[k] <= '9' ? s[k] - '0' : s[k] + 10 - 'A'))
              : 0;
    }
    flag = 25;
    for (int i = 0; i < 5; i++) {
      int key = calc(d, i);
      ans = (f[d][i][key] + c) % mo[i];
      for (int j = 0; j < 25; j++)
        if ((mo[i] % pri[j] == 0) && (ans % pri[j] == 0)) {
          flag = j;
          break;
        }
      if (flag < 25) break;
    }
    printf("%d\n", pri[flag]);
  }
  return 0;
}
