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
    List.fold_left (Array.fold_left ( && )) true
    [ Array.init n (fun i ->
        0 < i * l / n mod (l / m) ||
        s.[i] = t.[i * l / n / (l / m)]);
      Array.init m (fun i ->
        0 < i * l / m mod (l / n) ||
        t.[i] = s.[i * l / m / (l / n)]) ]
  then l
  else -1
