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) n, m = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) N = 5000 res = float('inf') P = [] for i, a in enumerate(A): for j, b in enumerate(B): if a == b: if i == j: res = min(res, i) else: P.append(5000*i+j) if math.gcd(n, m) != 1: if res != float('inf'): print(res) else: print(-1) exit() for p in P: i, j = divmod(p, 5000) r, M = CRT_list([i, j], [n, m]) if M == -1: continue else: res = min(r, res) if res != float('inf'): print(res+1) else: print(-1)