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