import sys

sys.setrecursionlimit(2147483647)

INF=float("inf")

MOD=10**9+7

input=lambda :sys.stdin.readline().rstrip()

def resolve():

    from fractions import gcd

    n,m=list(map(int,input().split()))

    s,t=[eval(input()) for _ in range(2)]

    gcd=gcd(n,m)

    lcm=n*m//gcd

    n//=gcd

    m//=gcd

    print((lcm if all(s[n*i]==t[m*i] for i in range(gcd)) else -1))

resolve()
import sys

INF = 1 << 60

MOD = 10**9 + 7 # 998244353

sys.setrecursionlimit(2147483647)

input = lambda:sys.stdin.readline().rstrip()

from math import gcd

def resolve():

    fixed = {}

    n, m = list(map(int, input().split()))

    S = eval(input())

    T = eval(input())

    l = n // gcd(n, m) * m

    for i in range(n):

        fixed[i * l // n] = S[i]

    for j in range(m):

        if not j * l // m in fixed:

            continue

        if fixed[j * l // m] != T[j]:

            print((-1))

            return

    print(l)

resolve()
import sys

sys.setrecursionlimit(2147483647)
INF = float("inf")
MOD = 10**9 + 7
input = lambda: sys.stdin.readline().rstrip()


def resolve():
    from fractions import gcd

    n, m = list(map(int, input().split()))
    s, t = [eval(input()) for _ in range(2)]
    gcd = gcd(n, m)
    lcm = n * m // gcd
    n //= gcd
    m //= gcd
    print((lcm if all(s[n * i] == t[m * i] for i in range(gcd)) else -1))


resolve()

import sys

INF = 1 << 60
MOD = 10**9 + 7  # 998244353
sys.setrecursionlimit(2147483647)
input = lambda: sys.stdin.readline().rstrip()
from math import gcd


def resolve():
    fixed = {}
    n, m = list(map(int, input().split()))
    S = eval(input())
    T = eval(input())
    l = n // gcd(n, m) * m
    for i in range(n):
        fixed[i * l // n] = S[i]
    for j in range(m):
        if not j * l // m in fixed:
            continue
        if fixed[j * l // m] != T[j]:
            print((-1))
            return
    print(l)


resolve()

+INF = 1 << 60 +MOD = 10**9 + 7  # 998244353 -INF = float("inf") -MOD = 10**9 + 7 +from math import gcd -    from fractions import gcd - +    fixed = {} -    s, t = [eval(input()) for _ in range(2)] -    gcd = gcd(n, m) -    lcm = n * m // gcd -    n //= gcd -    m //= gcd -    print((lcm if all(s[n * i] == t[m * i] for i in range(gcd)) else -1)) +    S = eval(input()) +    T = eval(input()) +    l = n // gcd(n, m) * m +    for i in range(n): +        fixed[i * l // n] = S[i] +    for j in range(m): +        if not j * l // m in fixed: +            continue +        if fixed[j * l // m] != T[j]: +            print((-1)) +            return +    print(l)