Problem:
 Score : 300 points    Problem Statement You are given a string S of length N and another string T of length M .
These strings consist of lowercase English letters.  A string X is called a good string when the following conditions are all met:   Let L be the length of X . L is divisible by both N and M .  Concatenating the 1 -st, (\frac{L}{N}+1) -th, (2 \times \frac{L}{N}+1) -th, ... , ((N-1)\times\frac{L}{N}+1) -th characters of X , without changing the order, results in S .  Concatenating the 1 -st, (\frac{L}{M}+1) -th, (2 \times \frac{L}{M}+1) -th, ... , ((M-1)\times\frac{L}{M}+1) -th characters of X , without changing the order, results in T .   Determine if there exists a good string. If it exists, find the length of the shortest such string.      Constraints  1 \leq N,M \leq 10^5  S and T consist of lowercase English letters.  |S|=N  |T|=M         Input Input is given from Standard Input in the following format:  N  M  S  T       Output If a good string does not exist, print -1 ; if it exists, print the length of the shortest such string.        Sample Input 1 3 2
acp
ae      Sample Output 1 6  For example, the string accept is a good string.
There is no good string shorter than this, so the answer is 6 .       Sample Input 2 6 3
abcdef
abc      Sample Output 2 -1       Sample Input 3 15 9
dnsusrayukuaiia
dujrunuma      Sample Output 3 45

Solution (Python):
import fractions


def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

def check():
    N, M = map(int, input().split())
    S = input()
    T = input()
    length = lcm(N,M)
        
    for i in [a*(length//N) for a in range(N)]:
        if i%(length//M)==0:
            if S[i//(length//N)] != T[i//(length//M)]:
                return -1
    return length
  
print(check())

Solution (Python):
from fractions import gcd
from functools import reduce

def lcm(a,b):
    return (a*b)//gcd(a,b)

def solve():
    N,M = map(int, input().split())
    S = input()
    T = input()
    gcd_NM = gcd(N,M)
    lcm_NM = (N*M)//gcd_NM
    S_diff = N // gcd_NM
    T_diff = M // gcd_NM
    
    i = 0
    possible = True
    while S_diff*i < N and T_diff*i < M:
        if S[S_diff*i] != T[T_diff*i]:
            possible = False
        i += 1
        
    print(lcm_NM if possible else -1)
    
solve()

Solution (Python):
from fractions import gcd

N, M = map(int, input().split())
S = input()
T = input()

lcm = N * M // gcd(N, M)
n = N // gcd(N, M)
m = M // gcd(N, M)

for k in range(gcd(N, M)):
    a = k * n
    b = k * m
    if S[a] != T[b]:
        print(-1)
        exit()

print(lcm)

Solution (Python):
from fractions import gcd

N, M = map(int, input().split())
S = input()
T = input()


def lcm(n, m):
    return n // gcd(n, m) * m


n = N // gcd(N, M)
m = M // gcd(N, M)

for i in range(gcd(N, M)):
    if S[i * n] != T[i * m]:
        print("-1")
        break
else:
    print(lcm(N, M))

Solution (Python):
import fractions
N,M=map(int,input().split())
S=input()
T=input()
lcm=(N*M)/fractions.gcd(N,M)
num=0
s=[]
t=[]
flag=1
sindex=0
tindex=0
while (sindex<N)and(tindex<M):
    if S[sindex]!=T[tindex]:
        flag=0
        break
    sindex=sindex+(N//fractions.gcd(N,M))
    tindex = tindex + (M // fractions.gcd(N, M))
"""
for j in range(N):
    s.append([S[j],int(1+(num//N)*j)-1])
for j in range(M):
    t.append([T[j], int(1 + (num // M) * j) - 1])

while (sindex<N)and(tindex<M):
    
    if s[sindex][1]==t[tindex][1]:
        if s[sindex][0]!=t[tindex][0]:
            flag=0
            break
        sindex=sindex+1
        tindex=tindex+1
    elif s[sindex][1]<t[tindex][1]:
        sindex=sindex+1
    else:
        tindex = tindex + 1
    
"""
if flag==0:
    print("-1")
else:
    print(int(lcm))

Solution (Python):
n,m=map(int,input().split())
s=input()
t=input()

from fractions import gcd
def lcm(a):
    x = a[0]
    for i in range(1, len(a)):
        x = (x * a[i]) // gcd(x, a[i])
    return x

long=lcm([n,m])

ln=int(long/n)
lm=int(long/m)



ok=True

for i in range(n-1):
    if (i*ln)%lm==0:
        if s[i]!=t[(i*ln)//lm]:
            ok=False

if n==1:
    if s!=t[0]:ok=False
if m==1:
    if t!=s[0]:ok=False

if not ok:long=-1

print(long)

Solution (Python):
n, m = map(int, input().split())
s = input()
t = input()
def gcd(a, b):
    if b == 0: return a
    if a < b: a, b = b, a
    return gcd(b, a%b)
def lcm(a, b):
    return a*b//gcd(a, b)
x = ""
nm = lcm(n, m)
N = {}
M = {}
for i in range(n):
    N[(nm//n)*i] = s[i]
for i in range(m):
    M[(nm//m)*i] = t[i]
if n > m:
    n, m = m, n
    N, M = M, N
f = True
g = lcm(nm//n, nm//m)
for i in N.keys():
    if i % g == 0:
        if N[i] != M[i]:
            f = False
if f: print(nm)
else: print(-1)

Solution (Python):
N, M = map(int, input().split())
S = input()
T = input()


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


L = lcm(N, M)


if S[::L//M] == T[::L//N]:
    print(L)
else:
    print(-1)

Solution (Python):
from fractions import gcd


def main():
    s_length, t_length = map(int, input().split())
    s = input()
    t = input()
    lcm = s_length * t_length // gcd(s_length, t_length)
    answer = True
    for i in range(s_length):
        if (i * t_length) % s_length == 0 and s[i] != t[(i * t_length) // s_length]:
            answer = False
            break
    print(lcm if answer else -1)


if __name__ == '__main__':
    main()

Solution (Python):

import sys
import fractions


def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

def solve(N: int, M: int, S: str, T: str):
    X = lcm(N,M)
    i = j = 0

    while i < N and j < M:
        if S[i] == T[j]:
            i += X//M
            j += X//N
            continue
        else:
            print(-1)
            return
    print(X)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    M = int(next(tokens))  
    S = next(tokens)  
    T = next(tokens)  
    solve(N, M, S, T)

if __name__ == '__main__':
    main()

Solution (Python):
import fractions


def binary_search(list, number, item):
    low = 0
    high = len(list) - 1

    while low <= high:
        mid = (low + high) // 2
        guess = list[mid][0]
        if guess == number:
            if list[mid][1] == item:
                return False
            else:
                return True
        if guess > number:
            high = mid - 1
        else:
            low = mid + 1
    
    return False


n, m = map(int, input().split())
s = input()
t = input()
check = []
l = n * m // fractions.gcd(n, m)
for i in range(n):
    check.append([i * l // n, s[i]])
for i in range(m):
    if binary_search(check, i * l // m, t[i]):
        print(-1)
        exit()
print(l)

Solution (Python):
from fractions import gcd
import sys
n, m = map(int, input().split())
s = input()
t = input()
if s[0]==t[0]:
    g = gcd(n, m)
    x = g*(n//g)*(m//g)
    num_s, num_t = x//n, x//m
    for i in range(0, x, num_s):
        if i%num_t==0 and s[i//num_s]!=t[i//num_t]:
            print(-1)
            sys.exit()
    print(x)
else:
    print(-1)

Solution (Python):
n,m = map(int, input().split())
s = input()
t = input()

def lcd(n, m):
    
    a = max(n,m)
    b = min(n,m)
    while b:
        a, b = b, a % b
    return n*m//a

l = lcd(n,m)
m1 = l//m
n1 = l//n

for i in range(n*m//l):
    a = m1*i 
    b = n1*i 
    if s[a] != t[b]:
        print(-1)
        exit()
print(l)

Solution (Python):
def main():
  n, m = input_list()
  s = input()
  t = input()
  gcm = fractions.gcd(n, m)
  lcm = (n*m)//gcm
  ng = n//gcm
  mg = m//gcm
  for i in range(gcm):
    if s[ng*i] != t[mg*i]:
      print(-1)
      exit(0)
  print(lcm)
  
def input_list():
  return list(map(int, input().split()))

def input_list_str():
  return map(str, input().split())

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

def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)

def gcd(*numbers):
    return reduce(fractions.gcd, numbers)

def gcd_list(numbers):
    return reduce(fractions.gcd, numbers)


def divide_two(arg):
  c = 0
  while True:
    if c >= 2:
      break
    if arg % 2 != 0:
      break
    arg //= 2
    c += 1
  return c 

import math
import fractions
import collections
from functools import reduce
main()

Solution (Python):
import fractions
N,M=map(int,input().split())
S=input()
T=input()
g=fractions.gcd(N,M);l=N*M//g
if(g==1):
    print(l if S[0]==T[0] else -1)
    exit()
a,b=0,0
n=N//g;m=M//g
while(a<N and b<M):
    if(S[a]!=T[b]):
        print(-1)
        exit()
    a+=n;b+=m
print(l)

Solution (Python):
import fractions
N,M=map(int,input().split())
S=input()
T=input()
g=fractions.gcd(N,M);l=N*M//g
if(g==1):
    print(l if S[0]==T[0] else -1)
    exit()
n=N//g;m=M//g
for i in range(g):
    if(S[n*i]!=T[m*i]):
        print(-1)
        exit()
print(l)

Solution (Python):
from collections import defaultdict
from fractions import gcd
def lcm(x, y):
    return (x * y) // gcd(x, y)

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

"""
存在するならば長さは必ずLである。
Lで存在しない場合、n * Lでも存在しない
"""
L = lcm(N, M)

X = defaultdict(str)

for p,s in enumerate(S):
    X[p * L // N] = s

flag = True
for q,t in enumerate(T):
    if X[q * L // M] and X[q * L // M] != t:
        flag = False
    else:
        X[q * L // M] = t

ans = L if flag else -1
print(ans)

Solution (Python):
from collections import defaultdict
from fractions import gcd
def lcm(x, y):
    return (x * y) // gcd(x, y)

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

L = lcm(N, M)

X = defaultdict(str)

for p,s in enumerate(S):
    X[p * L // N] = s

flag = True
for q,t in enumerate(T):
    if X[q * L // M] and X[q * L // M] != t:
        flag = False
    else:
        X[q * L // M] = t

if flag:
    print(L)
else:
    print(-1)

Solution (Python):
a,s=map(int,input().split())
sa,ss=[input() for i in range(2)]
if a<s:
    a,s=s,a
    sa,ss=ss,sa
from fractions import gcd
g=gcd(a,s)
x,y=a//g,s//g
for i in range(g):
    if sa[x*i]!=ss[y*i]:print(-1);break
else:print(x*s)

Solution (Python):

import sys

N,M = list(map(int, input().rstrip().split()))
S = input().strip()
T = input().strip()


def gcd(a,b):
    if b == 0: 
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return (a * b) // gcd(a, b)

lcm = lcm(N,M)
L = lcm
X1_dic={}

X1_dic[0] = S[0]
for i in range(1,N):
    X1_dic[ int(i*(L/N)+1) - 1 ] = S[i]


if X1_dic[0] != T[0]:
    print(-1)
    sys.exit()

for i in range(1,M):
    key = int(i*(L/M)+1) - 1
    if (key in X1_dic) and  X1_dic[key] != T[i]:
        print(-1)
        sys.exit()
    
print(L)

Solution (Python):
N, M = map(int, input().split())
S = str(input())
T = str(input())

from fractions import gcd
L = N * M // gcd(N, M)
step_s = L // M
step_t = L // N
stop = N // step_s
flag = True

for i in range(stop):
  
  if S[i * step_s] != T[i * step_t]:
    flag = False
    break

if flag:
  print(L)
else:
  print(-1)

Solution (Python):
from fractions import gcd

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

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

L1 = [0]
L2 = [0]

from collections import Counter
c = Counter()

for i in range(1, N):
    t = i * (L // N) + 1
    L1.append(t-1)

for i in range(1, M):
    t = i * (L // M) + 1
    L2.append(t-1)


d = {}
for i, li in enumerate(L1):
    d[li] = S[i]



ans = True

for i, li in enumerate(L2):
    if not d.get(li):
        continue
    if d[li] != T[i]:
        ans = False






if ans:
    print(L)
else:
    print(-1)

Solution (Python):
N, M = map(int, input().split(' '))
S = input()
T = input()

def gcd(a, b):
    if a < b:
        a, b = b, a

    if b == 0:
        return a

    else:
        return gcd(b, a - b)

lcm = N * M // gcd(N, M)
s_c_dict = dict([[j, S[i]] for i, j in enumerate(range(0, lcm, lcm//N))])
for i, j in enumerate(range(0, lcm, lcm//M)):
    if j in s_c_dict:
        if s_c_dict[j] != T[i]:
            print(-1)
            exit()
print(lcm)

Solution (Python):
import fractions
N,M=map(int,input().split())
S=input()
T=input()

n=N//fractions.gcd(N,M)
m=M//fractions.gcd(N,M)
g=fractions.gcd(N,M)
judge=True

for i in range(g):
    if S[i*n]!=T[i*m]:
        judge=False

if judge==True:
    print(N*M//g)
else:
    print(-1)

Solution (Python):
from fractions import gcd

def main():
    n, m = map(int, input().split())
    s = input().rstrip()
    t = input().rstrip()
    l = n*m // gcd(n, m)
    f = True
    for i in range(n):
        if i*m//n * n == i*m:
            j = i*m//n
            if s[i] != t[j]:
                f = False
    if f:
        print(l)
    else:
        print("-1")

if __name__ == "__main__":
    main()

Solution (Python):
import fractions
def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

n, m = map(int, input().split())
s = input()
t = input()
d = dict()
f = True

g = lcm(n, m)
nn = g // n
mm = g // m

for i in range(n):
    d[1 + nn * i] = s[i]

for i in range(m):
    if 1+mm*i in d:
        if d[1+mm * i] != t[i]:
            f = False
if f:
    print(g)
else:
    print(-1)

Solution (Python):
import fractions
n, m = map(int, input().split())
s = input()
t = input()
g = fractions.gcd(n, m)
r = (m*n)//g
n, m = n//g, m//g
for i in range(g):
    if s[i*n] != t[i*m]: r = False
if r: print(r)
else: print(-1)

Solution (Python):
n, m = list(map(int, input().split()))
s = input()
t = input()


import fractions
gcdd = fractions.gcd(n, m)

for i in range(gcdd):
    if s[i*(n//gcdd)] != t[i*(m//gcdd)]:
        print(-1)
        exit()

print(n*m//gcdd)

Solution (Python):

from fractions import gcd

N,M=map(int,input().split())
S=input()
T=input()
flg=True

g=gcd(N,M)
n,m=N//g,M//g

for k in range(0,g):
    if S[k*n]!=T[k*m]:
        flg=False

print(N*M//g if flg else -1)

Solution (Python):
import fractions

n,m = map(int, input().split())
s = input()
t = input()

gcd = fractions.gcd(n,m)

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

Solution (Python):
import fractions
N, M = map(int, input().split())
S = input()
T = input()
f = fractions.gcd(N, M)
flag = True
for i in range(f):
    if S[i*N//f] != T[i*M//f]:
        flag = False
        break
print([-1,N*M//f][flag])

Solution (Python):
from fractions import gcd
lcm=lambda x,y:x//gcd(x,y)*y
N,M=map(int, input().split())
S=input()
T=input()
g=gcd(N,M)
if all(S[N//g*i]==T[M//g*i] for i in range(g)):
    print(lcm(N,M))
else:
    print(-1)

Solution (Python):
def gcd(a, b):
	while b:
		a, b = b, a % b
	return a
def lcm(a, b):
	return a * b // gcd (a, b)
 
n,m = map(int,input().split())
s = input()
t = input()

l = lcm(n,m)
gaps = l//m
gapt = l//n

i,j = 0,0
while i<n:
    if s[i]!=t[j]:
        print(-1)
        break
    else:
        i += gaps
        j += gapt
else:
    print(l)

Solution (Python):
from fractions import gcd
x=input().split()
N=int(x[0])
M=int(x[1])
S=input()
T=input()
D=gcd(M,N)
OK=True
for l in range(D):
  if S[(l*N)//D]!=T[(l*M)//D]:
    OK=False
    break  
if OK==False:
  print(-1)
else:
  print((M*N)//D)

Solution (Python):
n, m = map(int, input().split())
s = input()
t = input()

from fractions import gcd

g = 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)

Solution (Python):
def gcd(a, b):
    if a > b:
        a, b = b, a
    while a % b != 0:
        a, b = b, a % b
    return b

def lcm(a, b):
    return a * b // gcd(a, b)

def solve(n, m, s, t):
    if s == t:
        return n
    else:
        l = lcm(n, m)
        dx = l // n
        dy = l // m
        x = 0
        y = 0
        cx = 0
        cy = 0
        while cx < n and cy < m:
            if x == y:
                if s[cx] != t[cy]:
                    return -1
                x += dx
                cx += 1
                y += dy
                cy += 1
            elif x < y:
                x += dx
                cx += 1
            else:
                y += dy
                cy += 1
        return l

_n, _m = map(int, input().split())
_s = input()
_t = input()
print(solve(_n, _m, _s, _t))

Solution (Python):
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
 

def ii(): return int(sys.stdin.readline().rstrip()) 
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) 
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]

def ss(): return sys.stdin.readline().rstrip() 
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) 
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]





n,m=mii()
s=ss()
t=ss()
if len(s) < len(t):
    s,t=t,s
    n,m=m,n

p=n*m//gcd(n,m)
q=gcd(n,m)
if s[0]==t[0]:

    x,y=n//gcd(n,m),m//gcd(n,m)
    cnt=1

    for i in range(gcd(n,m)-1):
        if s[i*x]==t[i*y]:
            cnt+=1
    if cnt==q:
        print(p)
    else:
        print(-1)

else:
    print(-1)

Solution (Python):
from fractions import gcd
N,M=map(int,input().split())
S=list(input())
T=list(input())
L=gcd(N,M)
print(N*M//L if all([S[i*N//L]==T[i*M//L] for i in range(L)]) else "-1")

Solution (Python):
import fractions
N, M = map(int, input().split())
S = input()
T = input()

if N < M:
    N, M = M, N
    S, T = T, S

if N % M == 0:
    print(N if all([S[(N // M) * i] == T[i] for i in range(M)]) else -1)
    exit()
else:
    g = fractions.gcd(N, M)
    print(N // g * M if all([S[(N // g) * i] == T[(M // g) * i] for i in range(g)]) else -1)

Solution (Python):

import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def roundUp(a, b):
        return -(-a // b)

    @staticmethod
    def toUpperMultiple(a, x):
        return Math.roundUp(a, x) * x

    @staticmethod
    def toLowerMultiple(a, x):
        return (a // x) * x

    @staticmethod
    def nearPow2(n):
        if n <= 0:
            return 0
        if n & (n - 1) == 0:
            return n
        ret = 1
        while(n > 0):
            ret <<= 1
            n >>= 1
        return ret

    @staticmethod
    def sign(n):
        if n == 0:
            return 0
        if n < 0:
            return -1
        return 1

    @staticmethod
    def isPrime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True


class PriorityQueue:
    def __init__(self, l=[]):
        self.__q = l
        heapq.heapify(self.__q)
        return

    def push(self, n):
        heapq.heappush(self.__q, n)
        return

    def pop(self):
        return heapq.heappop(self.__q)


MOD = int(1e09) + 7
INF = int(1e15)


def calc(N):
    return sum(int(x) for x in str(N))


def main():
    
    N, M = Scanner.map_int()
    S = Scanner.string()
    T = Scanner.string()
    L = Math.lcm(N, M)
    s, t = 0, 0
    while s < N and t < M:
        if S[s] != T[t]:
            print(-1)
            return
        s += L//M
        t += L//N
    print(L)
    return


if __name__ == "__main__":
    main()

Solution (Python):
N,M=map(int,input().split());import fractions;L=M//fractions.gcd(M,N)*N;print((-1,L)[input()[::L//M]==input()[::L//N]])

Solution (Python):
N,M=map(int,input().split())
import fractions
L=M//fractions.gcd(M,N)*N
print((-1,L)[input()[::L//M]==input()[::L//N]])

Solution (Python):
def gcd(a,b):
  if a<b:
    a,b=b,a
  while a%b>0:
    a,b=b,a%b
  return b

def lcm(a,b):
  return (a//gcd(a,b))*b

N,M=map(int,input().split())
S=input()
T=input()

length=lcm(N,M)
S=S[::length//M]
T=T[::length//N]
if S==T:
  print(length)
else:
  print(-1)

Solution (Python):
N,M=map(int,input().split())
S=input()
T=input()

def gcd(a,b):
  if a<b:
    a,b=b,a
  while a%b>0:
    a,b=b,a%b
  return b

def lcm(a,b):
  return (a//gcd(a,b))*b

length=lcm(N,M)
gapt=length//N
gaps=length//M
i=0
j=0
while i<N:
  if S[i]!=T[j]:
    print(-1)
    break
  else:
    i+=gaps
    j+=gapt
else:
  print(length)

Solution (Python):
n, m=map(int, input().split())
S=input()
T=input()

if n==1 and m==1:
  if S==T:
    print(1)
  else:
    print(-1)
  exit()
elif n==1 or m==1:
  print(-1)
  exit()

import fractions
p=n*m//fractions.gcd(n, m)
a=p//n
b=p//m
c=a*b//fractions.gcd(a, b)
for i in range(0, p, c):
  if S[i//a]!=T[i//b]:
    print(-1)
    exit()
    
print(p)

Solution (Python):
from fractions import gcd
def lcm(x,y):
    return x*y//gcd(x,y)
n,m = map(int,input().split())
s=input()
t=input()

l=lcm(n,m)
x=dict()

for i in range(n):
    x[i*(l//n)]=s[i]

for i in range(m):
    j=i*(l//m)
    if j in x and x[j]!=t[i]:
        print(-1)
        exit()
print(l)

Solution (Python):

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd(a, b)


n,m = map(int,input().split())
s = input()
t = input()

lc = lcm(n,m)

dic = {}

for i in range(len(s)):
    dic[lc//n*i] = s[i]
for i in range(len(t)):
    if lc//m*i in dic:
        if dic[lc//m*i] != t[i]:
            print(-1)
            exit()

print(lc)

Solution (Python):
N, M = map(int, input().split())
S = input()
T = input()

def gcd(x, y):
    while y != 0:
        x, y = y, x % y
    return x

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

L = lcm(N, M)
N_ = L // N
M_ = L // M

X = dict()
for i in range(N):
    X[i * N_] = S[i]

for i in range(M):
    j = i * M_
    if j in X and X[j] != T[i]:
        L = -1
        break

print(L)

Solution (Python):
def main():
    N, M = (int(i) for i in input().split())
    S = input()
    T = input()

    def gcd(x, y):
        if y == 0:
            return x
        while y != 0:
            x, y = y, x % y
        return x

    def lcm(x, y):
        return x*y//gcd(x, y)
    L = lcm(N, M)

    match = lcm(L//N, L//M)
    for a in range(0, L, match):
        if S[a * N//L] != T[a * M//L]:
            return print(-1)
    else:
        print(L)


if __name__ == '__main__':
    main()

Solution (Python):

n, m = map(int, input().split())
s = input()
t = input()

if s[0] != t[0]:
    print(-1)
    exit()
    


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)

l = lcm(n, m)
step = min(l//n, l//m)

for i in range(0, l, step):
    if i % (l//n) == 0 and i % (l//m) == 0:
        if s[i * n // l] != t[i * m // l]:
            print(-1)
            exit()
            

print(l)

Solution (Python):
from sys import stdin
import fractions


def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

n,m = [int(x) for x in stdin.readline().rstrip().split()]
s = stdin.readline().rstrip()
t = stdin.readline().rstrip()
koubai = lcm(n,m)

if s[::koubai//m] == t[::koubai//n]:
    print(koubai)
else:
    print(-1)

Solution (Python):
from fractions import gcd
n,m = map(int,input().split())
s = input()
t = input()
x = gcd(n,m)
if s[::n//x]==t[::m//x]:
  print(n*m//x)
else:
  print(-1)

Solution (Python):
from fractions import gcd
n,m = map(int,input().split())
s = input()
t = input()
x = gcd(n,m)
for i in range(x):
  if s[i*n//x]!=t[i*m//x]:
    print(-1)
    break
else:
  print(n*m//x)

Solution (Python):
def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd(a, b)


N, M = map(int, input().split())
S = input()
T = input()
gcd_val = gcd(N, M)
for i in range(gcd_val):
    if S[i * N // gcd_val] != T[i * M // gcd_val]:
        print(-1)
        exit()
print(lcm(N, M))

Solution (Python):
import fractions
N,M =list(map(int,input().split(" ")))
S = input()
T = input()
def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

ans = lcm(N,M)

step_S = ans //M
step_T = ans //N

ind_s = 0
ind_t = 0
while True:

    if ind_s >= N or ind_t >= M:
        break

    if S[ind_s ] != T[ind_t]:
        print(-1)
        exit(0)

    ind_s += step_S
    ind_t += step_T
print(ans)

Solution (Python):
import fractions
n, m = map(int, input().split())
s = input()
t = input()
sr = fractions.gcd(n, m)
sg, tg = n // sr, m // sr
for i in range(sr):
    if s[i * sg] != t[i * tg]:
        print(-1)
        exit()
print(sg * m)

Solution (Python):
import fractions
N,M = map(int,input().split())
S = input()
T = input()
gcd = fractions.gcd(N,M)
x = N // gcd 
y = M // gcd
check = 0
for i in range(gcd):
    if S[i*x] != T[i*y]:
        check = 1
        break
if check == 1:
    ans = -1
else:   
    ans = N * M // gcd
print(ans)

Solution (Python):
from fractions import gcd

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

S = input()
T = input()

G = gcd(N, M)

n = N // G
m = M // G

L = N * M // G

for i in range(0, G):
    a = i * n
    b = i * m

    if S[a] != T[b]:
        print(-1)
        exit()

print(L)

Solution (Python):
import math
import sys

def gcd(a,b):
	if b == 0:
		return a
	return gcd(b,a%b)


n,m = map(int, input().split())
s = input()
t = input()

if s[0] != t[0]:
	print(-1)
	sys.exit()

GCD = gcd(n,m)

if GCD == 1:
	print(n*m)
	sys.exit()

LCM = n*m//GCD


s_k = LCM//m
t_k = LCM//n
for i in range(GCD):
	if s[i*s_k] != t[i*t_k]:
		print(-1)
		sys.exit()

print(LCM)

Solution (Python):
from fractions import gcd

N, M = map(int,input().split())
S = input()
T = input()
L = (N*M)//gcd(N,M)
S_a = L // N
T_a = L // M
L_a = (S_a*T_a)//gcd(S_a,T_a)

S_b = L_a // S_a
T_b = L_a // T_a
i = 0
j = 0
while True:
    if S[i] != T[j]:
        print('-1')
        break
    i += S_b
    j += T_b
    if i >= N or j >= M:
        print(L)
        break

Solution (Python):
from fractions import gcd
def lcm(a,b):
    return(a*b//gcd(a,b))

N,M=map(int,input().split())
S,T=input(),input()

_lcm=lcm(N,M)
n=_lcm//N
m=_lcm//M
for i in range(0,_lcm,n*m):
    if S[i//n]!=T[i//m]:
        print(-1)
        exit()    
print(_lcm)

Solution (Python):
import fractions

n, m = map(int, input().split())
s = input()
t = input()

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

s_dic = {i * l//n + 1: s[i] for i in range(n)}
t_dic = {i * l//m + 1: t[i] for i in range(m)}

dup_idx = set(s_dic.keys()) & set(t_dic.keys())

for d in dup_idx:
    if s_dic[d] != t_dic[d]:
        print(-1)
        break
else:
    print(l)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e10


def solve():
    n,m = LI()
    s = S()
    t = S()
    def gcd(a, b):
        while b:
            a, b = b, a % b
        return a
    g = gcd(n, m)
    l = n * m // g
    n_ = n // g
    m_ = m // g
    for i in range(g):
        if s[n_ * i] != t[m_ * i]:
            print(-1)
            return
    print(l)
    return



if __name__ == '__main__':
    solve()

Solution (Python):
def gcd(a, b):
     while b:
         a, b = b, a%b
     return a

n, m = map(int, input().split())
s, t = input(), input()

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

a = [i*(l//n) for i in range(n)]
b = [i*(l//m) for i in range(m)]

x = set(a) & set(b)

for i in x:
    if s[a.index(i)] != t[b.index(i)]:
        print(-1)
        exit()

print(l)

Solution (Python):
import bisect
import math
import sys
from collections import defaultdict
from copy import copy
from heapq import heapify, heappop, heappush, heapreplace
from operator import itemgetter
from queue import LifoQueue, PriorityQueue, Queue

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


def main():
    N, M = map(int, readline().split())
    S, T = readlines()

    def gcd(a, b):
        while b > 0:
            a, b = b, a%b
        return a
    
    GCD = gcd(N, M)
    if S[0::N//GCD] == T[0::M//GCD]:
        print(N*M//GCD)
    else:
        print(-1)
    
if __name__ == "__main__":
    main()

Solution (Python):
import bisect
import math
import sys
from collections import defaultdict
from copy import copy
from heapq import heapify, heappop, heappush, heapreplace
from operator import itemgetter
from queue import LifoQueue, PriorityQueue, Queue

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


def main():
    N, M = map(int, readline().split())
    S, T = readlines()
    
    
    n, m = copy(N), copy(M)
    while m != 0:
        n, m = m, n%m
    if n == 1:
        if S[0] == T[0]:
            print(N*M)
        else:
            print(-1)
            
    
    else:
        L = N * M // n
        LN = L // N
        LM = L // M
        
        
        LCM = M // n * N // n
        for i in range(0, L, LCM):
            if S[i // LN] != T[i // LM]:    
                print(-1)
                sys.exit()

        print(L)


if __name__ == "__main__":
    main()

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from fractions import gcd

N,M = map(int,readline().split())
S = readline().rstrip().decode('utf-8')
T = readline().rstrip().decode('utf-8')

G = gcd(N,M)



A = ''.join(S[::N//G])
B = ''.join(T[::M//G])

if A == B:
    answer = N * M // G
else:
    answer = -1
print(answer)

Solution (Python):
import sys
import fractions
sys.setrecursionlimit(10**6)
if sys.platform in (['ios','darwin','win32']):
	sys.stdin=open('Untitled.txt')
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return [int(s) for s in input().split()]

def main():
	N, M = MAP()
	S = input().rstrip()
	T = input().rstrip()

	L = (N*M)//fractions.gcd(N, M)
	
	n = L//N
	m = L//M
	for i in range(0, L, n):
		if i % m == 0:
			if S[i//n] != T[i//m]:
				print(-1)
				sys.exit()
	print(L)


if __name__ == '__main__':
	main()