fun main(args : Array<String>) {
    val (n, m) = readLine()!!.split(" ").map { it.toInt() }
    val s = readLine()!!
    val t = readLine()!!

    val lcm = lcm(n.toLong(), m.toLong())
    if (lcm == n.toLong() * m.toLong()) {
        if (s[0] == t[0]) {
            println(lcm)
        } else {
            println("-1")
        }
        return
    }

    val stepN = lcm/n
    val stepM = lcm/m
    val stepC = lcm(stepN,  stepM)

    var idx = 0L

    while (idx < lcm) {
        if (s[(idx/stepN).toInt()] != t[(idx/stepM).toInt()]) {
            println("-1")
            return
        }
        idx += stepC
    }

    println(lcm)
}

fun gcd(a : Long, b : Long) : Long {
    return if (a % b == 0L) b else gcd(b, a % b)
}

fun lcm(a : Long, b : Long) : Long {
    return (a * b) / gcd(a, b)
}

