#include #include using namespace std; int main() { int N, M; cin >> N >> M; vector A(N), B(N); for (int i = 0; i < N; i++) cin >> A[i]; for (int i = 0; i < M; i++) cin >> B[i]; int64_t index = -1; for (int64_t i = 0; i < N * M; i++) { int64_t j = i % N; int64_t k = i % M; if (A[j] == B[k]) { index = i; break; } } if (index >= 0) index++; cout << index << std::endl; return 0; }