import fractions

import sys

input = sys.stdin.readline

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

S = eval(input()); T = eval(input())

gcd = fractions.gcd(N,M)

N_prime = N //gcd; M_prime = M // gcd

for i in range(0,N,N_prime):

    for j in range(0,M,M_prime):

        if i * M_prime - j * N_prime == 0 and S[i] != T[j]:

            print((-1))

            exit()

print((N*M // gcd))
from fractions import gcd

def lcm_base(x,y):

    return (x*y) // gcd(x,y)



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

S = eval(input())

T = eval(input())

ans = lcm_base(N,M)

for i in range(N):

    if M*i % N != 0:

        continue

    j = M*i // N

    if j >= M:

        continue

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

        print((-1))

        exit()

print(ans)
import fractions
import sys

input = sys.stdin.readline
N, M = list(map(int, input().split()))
S = eval(input())
T = eval(input())
gcd = fractions.gcd(N, M)
N_prime = N // gcd
M_prime = M // gcd
for i in range(0, N, N_prime):
    for j in range(0, M, M_prime):
        if i * M_prime - j * N_prime == 0 and S[i] != T[j]:
            print((-1))
            exit()
print((N * M // gcd))

from fractions import gcd


def lcm_base(x, y):
    return (x * y) // gcd(x, y)


N, M = list(map(int, input().split()))
S = eval(input())
T = eval(input())
ans = lcm_base(N, M)
for i in range(N):
    if M * i % N != 0:
        continue
    j = M * i // N
    if j >= M:
        continue
    if S[i] != T[j]:
        print((-1))
        exit()
print(ans)

-import fractions -import sys +from fractions import gcd -input = sys.stdin.readline + +def lcm_base(x, y): +    return (x * y) // gcd(x, y) + + -gcd = fractions.gcd(N, M) -N_prime = N // gcd -M_prime = M // gcd -for i in range(0, N, N_prime): -    for j in range(0, M, M_prime): -        if i * M_prime - j * N_prime == 0 and S[i] != T[j]: -            print((-1)) -            exit() -print((N * M // gcd)) +ans = lcm_base(N, M) +for i in range(N): +    if M * i % N != 0: +        continue +    j = M * i // N +    if j >= M: +        continue +    if S[i] != T[j]: +        print((-1)) +        exit() +print(ans)