import Control.Arrow
import Data.List
import qualified Data.ByteString.Char8 as B
import Control.Monad

main :: IO ()
main = breads >>= main'
    where
        main' [n, m] = replicateM 2 B.getLine >>= print . solve n m 

solve :: Int -> Int -> [B.ByteString] -> Int
solve n m [ss, ts]
    | i >= n || j >= m = l
    | B.index ss i == B.index ts j = l
    | otherwise = -1
    where
        l = lcm n m 
        i = l `div` m
        j = l `div` n 

breads :: IO [Int]
breads = unfoldr (\s -> second (maybe B.empty snd . B.uncons) <$> B.readInt s) <$> B.getLine