#include using namespace std; const int MAXN = 15e5 + 7; const unsigned int base = 203; int d[MAXN]; unsigned int a[MAXN], times[MAXN]; int n, m; int calc_times(int x){ if(x == 0) return -1; int x2 = x, ret = 0; for(int i = 0; i < m; ++i){ while(x2 % d[i] == 0){ x2 /= d[i]; ++ret; } } x2 = x; while(x2 > 0){ int curr = (x2 % 10); for(int i = 0; i < m; ++i){ if(d[i] == curr) ++ret; } x2 /= 10; } return ret; } int main(){ ios::sync_with_stdio(false); cin.tie(NULL); freopen("tsuk.in", "r", stdin); freopen("tsuk.out", "w", stdout); cin >> m; for(int i = 0; i < m; ++i){ cin >> d[i]; } cin >> n; for(int i = 0; i < n; ++i){ cin >> a[i]; } for(int i = 1; i < MAXN; ++i){ times[i] = calc_times(i); } unsigned long long our_hash = 0; for(int i = 0; i < n; ++i){ our_hash *= base; our_hash += a[i]; } unsigned long long curr_hash = 0, power = 1; for(int i = 1; i <= n; ++i){ curr_hash *= base; curr_hash += times[i]; power *= base; } if(curr_hash == our_hash){ cout << times[n + 1] << "\n"; return 0; } for(int i = n + 1; i < MAXN; ++i){ curr_hash *= base; curr_hash -= power * times[i - n]; curr_hash += times[i]; if(curr_hash == our_hash){ cout << times[i + 1] << "\n"; return 0; } } return -3; } /* 2 5 7 6 0 3 0 1 1 0 */