def extgcd(a, b): if b == 0: return 1, 0, a q, r = divmod(a, b) x, y, d = extgcd(b, r) s, t = y, x-q*y return s, t, d def MOD(a, m): return (a%m + m)%m; def CRT_list(b, m): # b: list # m: list # x ≡ bi (mod mi)を満たすx ≡ r (mod lcm(m1*m2..*mn))について # r, lcm(m1*m2..*mn)をreturn # 解無しの場合は0, -1をreturn r, M = 0, 1 for i in range(len(b)): p, q, d = extgcd(M, m[i]) if (b[i]-r)%d != 0: return 0, -1 temp = (b[i]-r)//d * p % (m[i]//d) r += M * temp M *= m[i]//d return MOD(r, M), M import math from functools import reduce def lcm_base(x, y): return (x * y) // math.gcd(x, y) def lcm_list(numbers): return reduce(lcm_base, numbers, 1) import sys import io, os #input = sys.stdin.buffer.readline input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, m = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) N = 5000 INF = 10**18 res = INF P = [] for i, a in enumerate(A): for j, b in enumerate(B): if a == b: if i == j: if i <= res: res = i else: P.append(5000*i+j) m = [n, m] for x in P: i, j = divmod(x, 5000) b = [i, j] r, M = 0, 1 for i in range(len(b)): p, q, d = extgcd(M, m[i]) if (b[i]-r)%d != 0: r, M = 0, -1 break temp = (b[i]-r)//d * p % (m[i]//d) r += M * temp M *= m[i]//d if M != -1: if r <= res: res = r if res != INF: print(res+1) else: print(-1)