INF = 10 ** 15 N, M = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) result = INF for i in range(N): a = A[i] for j in range(M): x = i + j * N if x > result: break b = B[x % M] if a != b: continue result = min(result, x) break if result == INF: print(-1) else: print(result)