import sys

import fractions

N, M = list(map(int, input().split()))

S = eval(input())

T = eval(input())



g = fractions.gcd(N, M)

L = N * M // g



ss = L // N

ts = L // M

for i in range(N):

  if (i * ss) % ts == 0:

    j = (i * ss) // ts

    if S[i] != T[j]:

      print((-1))

      sys.exit()



for i in range(M):

  if (i * ts) % ss == 0:

    j = (i * ts) // ss

    if T[i] != S[j]:

      print((-1))

      sys.exit()



print(L)
import sys

import fractions

N, M = list(map(int, input().split()))

S = eval(input())

T = eval(input())



g = fractions.gcd(N, M)

L = N * M // g



def check(U1, U2):

  s1 = L // len(U1)

  s2 = L // len(U2)

  for i in range(len(U1)):

    if (i * s1) % s2 == 0:

      j = (i * s1) // s2

      if U1[i] != U2[j]:

        return False

  return True



if check(S, T) and check(T, S):

  print(L)

else:

  print((-1))
import sys
import fractions

N, M = list(map(int, input().split()))
S = eval(input())
T = eval(input())
g = fractions.gcd(N, M)
L = N * M // g
ss = L // N
ts = L // M
for i in range(N):
    if (i * ss) % ts == 0:
        j = (i * ss) // ts
        if S[i] != T[j]:
            print((-1))
            sys.exit()
for i in range(M):
    if (i * ts) % ss == 0:
        j = (i * ts) // ss
        if T[i] != S[j]:
            print((-1))
            sys.exit()
print(L)

import sys
import fractions

N, M = list(map(int, input().split()))
S = eval(input())
T = eval(input())
g = fractions.gcd(N, M)
L = N * M // g


def check(U1, U2):
    s1 = L // len(U1)
    s2 = L // len(U2)
    for i in range(len(U1)):
        if (i * s1) % s2 == 0:
            j = (i * s1) // s2
            if U1[i] != U2[j]:
                return False
    return True


if check(S, T) and check(T, S):
    print(L)
else:
    print((-1))

-ss = L // N -ts = L // M -for i in range(N): -    if (i * ss) % ts == 0: -        j = (i * ss) // ts -        if S[i] != T[j]: -            print((-1)) -            sys.exit() -for i in range(M): -    if (i * ts) % ss == 0: -        j = (i * ts) // ss -        if T[i] != S[j]: -            print((-1)) -            sys.exit() -print(L) + + +def check(U1, U2): +    s1 = L // len(U1) +    s2 = L // len(U2) +    for i in range(len(U1)): +        if (i * s1) % s2 == 0: +            j = (i * s1) // s2 +            if U1[i] != U2[j]: +                return False +    return True + + +if check(S, T) and check(T, S): +    print(L) +else: +    print((-1))