from collections import defaultdict def Ext_gcd(a,b): #GCD,x,yを返す。ax +by = GCD if b == 0: return (a,1,0) g,y,x = Ext_gcd(b,a%b) y -= a//b*x return (g,x,y) def ChiniseRem(b1,m1,b2,m2): g,p,q = Ext_gcd(m1,m2) if (b1-b2)%g != 0: return (0,-1) m = m1*m2//g temp = (b2-b1)//g*p%(m2//g) x = (b1 + m1*temp)%m return (x,m) def main(): N,M = map(int,input().split()); INF = float("inf") A = list(map(int,input().split())) B = list(map(int,input().split())) adic = defaultdict(list) bdic = defaultdict(list) for i,a in enumerate(A): adic[a].append(i) for i,b in enumerate(B): bdic[b].append(i) #print(adic) #print(bdic) ans = INF for a in adic: if a not in bdic: continue for p in adic[a]: for q in bdic[a]: #print(a,p,q) x,m = ChiniseRem(p,N,q,M) if x == 0: continue #print(x) ans = min(ans, x) if ans == INF: print(-1) else: print(ans+1) if __name__ == '__main__': main()