program name
    use,intrinsic :: iso_fortran_env
    implicit none
    integer(int64):: n,m,i,nn,mm, si,ti
    character(:),allocatable:: s,t

    read*, n,m
    allocate(character(n):: s)
    allocate(character(m):: t)
    read*, s
    read*, t
    nn = lcm(n,m)/n
    mm = lcm(n,m)/m

    do i=1,n/mm
        si = mm*(i-1)+1
        ti = nn*(i-1)+1

        if (s(si:si) /= t(ti:ti)) then
            print'(i0)', -1
            stop
        end if
    end do
    print'(i0)', lcm(n,m)
contains
    function lcm(x,y) result(ret)
        integer(int64):: x,y,ret

        ret=x*y/gcd(x,y)
    end function

    recursive function gcd(x,y) result(ret)
    integer(int64):: x,y,ret

    if (mod(x,y) == 0) then
        ret = y
        return
    end if

    ret = gcd(y,mod(x,y))
end function
end program name