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