function gcd(u, v)
  while v ~= 0 do
    u, v = v, u%v
  end
  return u
end

function lcm(u,v)
  return u * v / gcd(u, v)
end

N, M = string.match(io.read(), "(%d) (%d)")

L = lcm(N,M)
ans = L

oS = L/N
oT = L/M

X = {}
p = 1
for v = 1, N do
  X[p] = io.read(1)
  p = p + oS
end
io.read()

p = 1
for v = 1, M do
  c = io.read(1)
  if not (X[p] == nil or X[p] == c) then
    ans = -1
    break
  end
  p = p + oT
end
io.read()

print(string.format("%d",ans))
