import math

def main4():

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

    S = eval(input())

    T = eval(input())



    L = (N * M) // math.gcd(N, M)



    pair = dict()



    for i in range(1, N + 1):

        idx = (i - 1) * (L // N) + 1

        pair[idx] = S[i - 1]



    for i in range(1, M + 1):

        idx = (i - 1) * (L // M) + 1



        if idx in list(pair.keys()):

            if pair[idx] != T[i - 1]:

                print((-1))

                exit()



    print(L)



if __name__ == "__main__":

    main4()
import math

def main5():

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

    S = eval(input())

    T = eval(input())



    G = math.gcd(N, M)

    L = (N * M) // G



    for i in range(G):

        if S[i * N // G] != T[i * M // G]:

            print((-1))

            exit()



    print(L)



if __name__ == "__main__":

    main5()
import math


def main4():
    N, M = list(map(int, input().split()))
    S = eval(input())
    T = eval(input())
    L = (N * M) // math.gcd(N, M)
    pair = dict()
    for i in range(1, N + 1):
        idx = (i - 1) * (L // N) + 1
        pair[idx] = S[i - 1]
    for i in range(1, M + 1):
        idx = (i - 1) * (L // M) + 1
        if idx in list(pair.keys()):
            if pair[idx] != T[i - 1]:
                print((-1))
                exit()
    print(L)


if __name__ == "__main__":
    main4()

import math


def main5():
    N, M = list(map(int, input().split()))
    S = eval(input())
    T = eval(input())
    G = math.gcd(N, M)
    L = (N * M) // G
    for i in range(G):
        if S[i * N // G] != T[i * M // G]:
            print((-1))
            exit()
    print(L)


if __name__ == "__main__":
    main5()

-def main4(): +def main5(): -    L = (N * M) // math.gcd(N, M) -    pair = dict() -    for i in range(1, N + 1): -        idx = (i - 1) * (L // N) + 1 -        pair[idx] = S[i - 1] -    for i in range(1, M + 1): -        idx = (i - 1) * (L // M) + 1 -        if idx in list(pair.keys()): -            if pair[idx] != T[i - 1]: -                print((-1)) -                exit() +    G = math.gcd(N, M) +    L = (N * M) // G +    for i in range(G): +        if S[i * N // G] != T[i * M // G]: +            print((-1)) +            exit() -    main4() +    main5()