module Main where import Data.List (findIndex) type Input = (Int, Int, [Int], [Int]) type Output = Int parse :: String -> Input parse s = let reads = \pos -> map read . words . pos $ lines s [n, m] = reads head a = reads (!! 1) b = reads (!! 2) in (n, m, a, b) solve :: Input -> Output solve (n, m, a, b) = maybe (-1) succ . findIndex (uncurry (==)) . take (lcm n m) . zip (cycle a) $ cycle b render :: Output -> String render = show main :: IO () main = interact ( render . solve . parse )