#include #define rep(i, l, r) for (int i = (l); i < (r); i++) using namespace std; typedef long long ll; int main() { int N, M; cin >> N >> M; vector A(N), B(M); rep(i, 0, N) cin >> A[i]; rep(i, 0, M) cin >> B[i]; rep(i, 0, N * M) { if (A[i % N] == B[i % M]) { cout << i + 1 << endl; return 0; } } cout << -1 << endl; }