n,m = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) len_a,len_b = len(a),len(b) import math ans = -1 LMC = len_a * len_b // math.gcd(len_a,len_b) for i in range(LMC): # print(a[i % len_a],b[i % len_b],i+1) if a[i % len_a] == b[i % len_b]: ans = i+1 break print(ans)