from math import lcm from itertools import cycle N, M = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) t = lcm(N, M) for i, (a, b) in enumerate(zip(cycle(A), cycle(B))): if i == t: break if a == b: print(i+1) exit() print(-1)