#include <bits/stdc++.h>
#pragma GCC optimize "-O3"
#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC target("avx")
using namespace std;
bool is_prm(int a) {
  for (int i = 2; i < a; i++) {
    if (a % i == 0) return 0;
  }
  return 1;
}
int main() {
  long long c;
  int n, i, j, k, l, r, len;
  int d, M, mx, p, B, test;
  char s[111];
  vector<long long> a;
  vector<int> I;
  vector<int> lng(30, 0);
  vector<int> tmp(30, 0);
  vector<int> pow(30, 1);
  vector<int> prm;
  vector<int> dyna[17][4];
  vector<int> MOD = {300690390, 1808691197, 2044926619, 2073080791};
  for (i = 2; i < 100; i++) {
    if (is_prm(i)) {
      prm.emplace_back(i);
    }
  }
  I.resize(prm.size());
  for (i = 0; i < prm.size(); i++) {
    for (j = 0; j < MOD.size(); j++) {
      if (MOD[j] % prm[i] == 0) {
        I[i] = j;
        break;
      }
    }
  }
  scanf("%d", &n);
  a.resize(n);
  for (auto& r : a) scanf("%I64d", &r);
  for (l = 2; l < 17; l++) {
    for (r = mx = 1, B = l + 1; r < n; r *= l, mx *= B, lng[l]++)
      ;
    for (i = 1; i < lng[l]; i++) {
      pow[i] = pow[i - 1] * B;
    }
    for (i = 0; i < 4; i++) {
      dyna[l][i].resize(mx + 1);
    }
    for (i = 0; i < mx; i++) {
      for (j = 0, M = i, p = -1; j < lng[l]; j++) {
        tmp[j] = M % B;
        M /= B;
        if (tmp[j] == l) p = j;
      }
      for (j = 0; j < 4; j++) {
        dyna[l][j][i] = 1;
      }
      if (~p) {
        for (j = 0; j < 4; j++) {
          for (k = 1; k <= l; k++) {
            dyna[l][j][i] =
                1ll * dyna[l][j][i] * dyna[l][j][i - k * pow[p]] % MOD[j];
          }
        }
      } else {
        for (j = lng[l], M = 0; j--;) {
          M = M * l + tmp[j];
        }
        if (M < n) {
          for (j = 0; j < 4; j++) {
            dyna[l][j][i] = a[M] % MOD[j];
          }
        }
      }
    }
  }
  scanf("%d", &test);
  while (test--) {
    scanf("%d%s%I64d", &d, &s, &c);
    len = strlen(s);
    for (i = max(0, len - lng[d]), mx = 0; i < len; i++) {
      if (s[i] == '?')
        j = d;
      else if (isalpha(s[i]))
        j = s[i] - 'A' + 10;
      else
        j = s[i] - '0';
      mx = mx * (d + 1) + j;
    }
    for (i = 0, k = -1; i < prm.size() && !~k; i++) {
      if (!((c + dyna[d][I[i]][mx]) % prm[i])) {
        k = prm[i];
      }
    }
    printf("%d\n", k);
  }
  return 0;
}
