import sys readline=sys.stdin.readline write=sys.stdout.write N,M=map(int,readline().split()) A=list(map(int,readline().split())) B=list(map(int,readline().split())) for nm in range(N*M): if A[nm%N]==B[nm%M]: ans=nm+1 break else: ans=-1 print(ans)