import math N, M = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) G = math.gcd(N, M) L = N*M//G for i in range(L): if A[i%N]==B[i%M]: print(i+1) exit() print(-1)