nu1,nu2 = gets.chomp.split(" ").map(&:to_i)
nu = [nu1, nu2]
wo1 = gets.chomp.split("")
wo2 = gets.chomp.split("")
if wo1[0] != wo2[0]
  puts "-1"
  exit
end
pr = []
require 'prime'
Prime.each(10**5) do |prime|
  pr.push(prime)
end
nu1_p = Array.new(pr.length, 0)
nu2_p = Array.new(pr.length, 0)
for i in 1..pr.length
  if nu1 % pr[i - 1] == 0
    while nu1 % pr[i - 1] == 0
      nu1 /= pr[i - 1]
      nu1_p[i - 1] += 1
    end
  end
end
for i in 1..pr.length
  if nu2 % pr[i - 1] == 0
    while nu2 % pr[i - 1] == 0
      nu2 /= pr[i - 1]
      nu2_p[i - 1] += 1
    end
  end
end
min = 1
for i in 1..pr.length
  if (nu1_p[i - 1] >= nu2_p[i - 1])
    if pr[i - 1]*nu1_p[i - 1] != 0
      min *= pr[i - 1]**nu1_p[i - 1]
    end
  elsif (nu1_p[i - 1] < nu2_p[i - 1])
    if pr[i - 1]*nu2_p[i - 1] != 0
      min *= pr[i - 1]**nu2_p[i - 1]
    end
  end
end
nu3 = min / nu[0]
nu4 = min / nu[1]
count = 1 + (min / nu[0])*nu4
count1 = (min / nu[1]) + 1
count2 = (min / nu[0]) + 1
while count <= min
  if wo1[count1 - 1] != wo2[count2 - 1]
    puts "-1"
    exit
  end
  count += (min / nu[0])*nu4
  count1 += (min / nu[1])
  count2 += (min / nu[0])
end
puts min
