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] = check 0
    where
        check x
            | s >= n || t >= m = l
            | B.index ss s == B.index ts t = check $ x + 1 
            | otherwise = -1
            where
                s = i * x
                t = j * x
        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