//Normal #define _GLIBCXX_DEBUG #define ll long long #include using namespace std; using Graph = vector>; void print(auto a){ cout << a; } void prints(auto a){ cout << a << " "; } void prints(){ cout << " "; } void printl(auto a){ cout << a << endl; } void printl(){ cout << endl; } void fix(int n){ cout << fixed << setprecision(n); } int siz(string s){ return (int)s.size(); } int main(){ int N, M; cin >> N >> M; vector A(N), B(M); map mp; for(int i = 1; i <= N; i++){ cin >> A[i%N]; mp[A[i%N]]++; } bool flag = false; for(int i = 1; i <= M; i++){ cin >> B[i%M]; if(mp[B[i%M]] > 0){ flag = true; } } if(!flag){ printl(-1); }else{ for(int i = 1; i <= N*M; i++){ if(A[i%N] == B[i%M]){ printl(i); return 0; } } printl(-1); return 0; } return 0; }