def gcd(x, y): while y: x, y = y, x%y return x def main(): N, M = map(int, input().split()) X = list(map(int, input().split())) Y = list(map(int, input().split())) for i in range(x*y//gcd(x, y)): if X[i%N] == Y[i%M]: return i return "-1" if __name__ == "__main__": main()