#include <bits/stdc++.h>
using namespace std;
const long long prime[26] = {0,  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 mod[5] = {0, 300690390, 2044926619, 1808691197, 2073080791};
long long n, m, i, j, k, p, d, c, len, tmp;
long long a[10005], v[35];
vector<long long> vec[17][5];
string s;
bool vis[27];
long long get() {
  long long p = 0;
  char x = getchar();
  while (x < '0' || x > '9') x = getchar();
  while (x >= '0' && x <= '9') {
    p = p * 10 + x - '0';
    x = getchar();
  }
  return p;
}
void print() {
  for (i = 1; i <= 25; ++i)
    if (vis[i]) {
      printf("%d\n", prime[i]);
      return;
    }
  printf("-1\n");
  return;
}
long long solve(long long Prr) {
  long long i, j, now = 0, temp = 0;
  for (i = 1; i <= len; ++i) {
    now = now * (d + 1) + v[i];
  }
  if (vec[d][Prr][now] != -1) return vec[d][Prr][now];
  vec[d][Prr][now] = 1;
  for (i = 1; i <= len; ++i)
    if (v[i] == d) {
      for (j = 0; j < d; ++j) {
        v[i] = j;
        vec[d][Prr][now] = (vec[d][Prr][now] * solve(Prr)) % mod[Prr];
      }
      v[i] = d;
      return vec[d][Prr][now];
    }
  for (i = 1; i <= len; ++i) {
    temp = temp * d + v[i];
  }
  if (temp + 1 <= n) vec[d][Prr][now] = a[temp + 1] % mod[Prr];
  return vec[d][Prr][now];
}
void read() {
  n = get();
  for (i = 1; i <= n; ++i) {
    a[i] = get();
  }
  for (i = 2; i <= 16; ++i) {
    for (j = 1, k = 1; j <= n; j *= i, k *= i + 1) {
    }
    for (p = 1; p <= 4; ++p) vec[i][p].resize(k + 2, -1);
  }
  m = get();
  while (m--) {
    d = get();
    cin >> s;
    c = get();
    for (i = 0; i <= s.length(); ++i) {
      v[i] = 0;
    }
    for (j = 1, len = 0; j <= n; j *= d, len++) {
    }
    for (i = 1; i <= len; ++i) {
      j = s.length() - len + i - 1;
      if (j < 0) continue;
      if (s[j] == '?')
        v[i] = d;
      else {
        if (s[j] >= '0' && s[j] <= '9')
          v[i] = s[j] - '0';
        else
          v[i] = s[j] - 'A' + 10;
      }
    }
    memset(vis, false, sizeof(vis));
    for (i = 1; i <= 4; ++i) {
      tmp = solve(i);
      tmp = (tmp + (c % mod[i])) % mod[i];
      for (j = 1; j <= 25; ++j)
        if (!(mod[i] % prime[j]) && !(tmp % prime[j])) {
          vis[j] = true;
        }
    }
    print();
  }
  return;
}
int main() {
  read();
  return 0;
}
