require 'prime'
N, M = gets.split.map(&:to_i) 
S = gets.chomp
T = gets.chomp

def test(n, m)
  i = j = 0
  while i < N && j < M
    #p [i, j, S[i], T[j]]
    return false if S[i] != T[j]
    i += n
    j += m
  end
  return true
end

def test2(n, m, len)
  lcm = n.lcm(m)
  i = 1
  loop do
    k = (i * lcm + 1)
    s = (k - 1) / n
    t = (k - 1) / m
    return false if S[s] != T[t]
    break if k > lcm
  end
  return true
end

lcm = N.lcm(M) 
ok = if S[0] != T[0]
       false
     elsif lcm == N
       test(lcm/M, 1)
     elsif lcm == M
       test(1, lcm/N)
     else
       test2(lcm/N, lcm/M, lcm)
     end
p(ok ? lcm : -1)
