from math import gcd def solve(): n, m = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) i = j = 0 x = 1 ans = -1 for _ in range(n * m // gcd(n, m)): if A[i] == B[j]: ans = x break x += 1 if i == n - 1: i = 0 else: i += 1 if j == m - 1: j = 0 else: j += 1 print(ans) solve()