#include <bits/stdc++.h>
using namespace std;
const int Number[25] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1,
                        1, 1, 2, 2, 3, 2, 3, 3, 3, 3, 2, 2};
const int Prime[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 Mod[4] = {300690390, 2044926619, 1808691197, 2073080791};
struct Data {
  int X[4];
};
Data operator*(Data A, Data B) {
  Data C;
  for (int i = 0; i < 4; i++) C.X[i] = (long long)A.X[i] * B.X[i] % Mod[i];
  return C;
}
int Get(char c, int Base) {
  return (c == '?') ? Base : (c - ((c <= '9') ? 48 : 55));
}
Data Make(long long V) {
  Data Temp;
  for (int i = 0; i < 4; i++) Temp.X[i] = V % Mod[i];
  return Temp;
}
int N;
long long V[10000];
int Len[17];
vector<Data> DP[17];
void Init(int Base) {
  int S = Base, Total = Base + 1;
  Len[Base] = 1;
  while (S < N) {
    S *= Base;
    Total *= Base + 1;
    Len[Base]++;
  }
  DP[Base].resize(Total);
  int Pow[14];
  for (int i = Pow[0] = 1; i < Len[Base]; i++) Pow[i] = Pow[i - 1] * (Base + 1);
  for (int Mask = 0; Mask < Total; Mask++) {
    DP[Base][Mask] = Make(1);
    int Temp = Mask, A[14];
    for (int i = 0; i < Len[Base]; i++) {
      A[i] = Temp % (Base + 1);
      Temp /= Base + 1;
    }
    int P = Len[Base] - 1;
    while (P >= 0 && A[P] < Base) P--;
    if (P < 0) {
      Temp = 0;
      for (int i = Len[Base] - 1; i >= 0; i--) Temp = Temp * Base + A[i];
      if (Temp < N) DP[Base][Mask] = Make(V[Temp]);
    } else
      for (int i = 1; i <= Base; i++)
        DP[Base][Mask] = DP[Base][Mask] * DP[Base][Mask - i * Pow[P]];
  }
}
int main() {
  scanf("%d", &N);
  for (int i = 0; i < N; i++) cin >> V[i];
  for (int i = 2; i <= 16; i++) Init(i);
  int Query;
  scanf("%d", &Query);
  while (Query--) {
    int Base;
    scanf("%d", &Base);
    string S;
    cin >> S;
    int Mask = 0;
    for (int i = max((int)S.size() - Len[Base], 0); i < S.size(); i++)
      Mask = Mask * (Base + 1) + Get(S[i], Base);
    Data T = DP[Base][Mask];
    long long Delta;
    cin >> Delta;
    int Ans = -1;
    for (int i = 0; i < 25 && Ans == -1; i++)
      if (!((Delta + T.X[Number[i]]) % Prime[i])) Ans = Prime[i];
    printf("%d\n", Ans);
  }
  return 0;
}
