import sys INF = float('inf') MOD = 10**9 + 7 MOD2 = 998244353 def solve(): def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def LC(): return list(input()) def IC(): return [int(c) for c in input()] def MI(): return map(int, sys.stdin.readline().split()) def egcd(a, b): if a == 0: return b, 0, 1 else: g, y, x = egcd(b % a, a) return g, x - (b // a) * y, y def chineseRem(b1, m1, b2, m2): # 中国剰余定理 # x ≡ b1 (mod m1) ∧ x ≡ b2 (mod m2) <=> x ≡ r (mod m) # となる(r. m)を返す # 解無しのとき(0, -1) d, p, q = egcd(m1, m2) if (b2 - b1) % d != 0: return 0, -1 m = m1 * (m2 // d) # m = lcm(m1, m2) tmp = (b2 - b1) // d * p % (m2 // d) r = (b1 + m1 * tmp) % m return r, m N,M = MI() A = LI() B = LI() Ans = INF for a in range(N): for b in range(M): if(A[a] == B[b]): R = [a, b] r, m = chineseRem(a,N,b,M) if (r == 0 and m == -1): continue if (Ans > r + 1): Ans = r + 1 if(Ans == INF): print(-1) exit() print(Ans) return solve()