import math INF=float('inf') def lcm(a,b): return a*b//math.gcd(a,b) def two_crt(mod1,mod2,i,j): g=math.gcd(mod1,mod2) if i%g!=j%g: return INF else: INV=pow(mod1//g,-1,mod2//g) return (i+(((j-i)//g)*mod1*INV))%lcm(mod1,mod2) def crt(L): thismod=L[0][0] thisnum=L[0][1] for i in range(1,len(L)): thisnum=two_crt(thismod,L[i][0],thisnum,L[i][1]) thismod=lcm(thismod,L[i][0]) return thisnum,thismod N,M=map(int,input().split()) L=list(map(int,input().split())) R=list(map(int,input().split())) ans=10**10 for i in range(N): for j in range(M): if L[i]==R[j]: a=two_crt(N,M,i,j) if a==INF: continue else: ans=min(ans,a) if ans==10**10: print(-1) else: print(ans+1)