let rec gcd n m =
  if m = 0 then n
  else gcd m (n mod m)

let lcm n m = n / gcd n m * m

let () = Scanf.scanf "%d %d\n%s\n%s" @@ fun n m s t ->
  Printf.printf "%d\n" @@
  let l = lcm n m in
  if
    Array.fold_left ( && ) true @@
    Array.init l @@ fun i ->
      0 < i mod (l / n) ||
      0 < i mod (l / m) ||
      s.[i * n / l] = t.[i * m / l]
  then l
  else -1
