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 in Rust (1.15.1) (judge verdict: Time Limit Exceeded)

use std::cmp::*;
use std::collections::*;
use std::io::*;
use std::str::FromStr;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o);
    stdout().write_all(&o).unwrap();
}

fn run<R: BufRead, W: Write>(i: R, o: &mut W) {
    let mut i = CpReader::new(i);
    let (_n, _m) = i.read2::<usize, usize>();
    let s: Vec<u8> = i.read_line().as_bytes().iter().cloned().collect();
    let t: Vec<u8> = i.read_line().as_bytes().iter().cloned().collect();

    if let Some(len) = solve(&s, &t) {
        writeln!(o, "{}", len).unwrap();
    } else {
        writeln!(o, "-1").unwrap();
    }
}
fn solve(s: &[u8], t: &[u8]) -> Option<usize> {
    let len = lcm(s.len(), t.len());
    for is in 0..s.len() {
        if is * t.len() % s.len() == 0 {
            let it = is * t.len() / s.len();
            if s[is] != t[it] {
                return None;
            }
        }
    }
    Some(len)
}

fn prime_factorization(mut x: usize) -> Vec<usize> {
    let mut rs = Vec::new();
    if x == 0 {
        return rs;
    }
    let mut n = 2;
    loop {
        while x % n == 0 {
            rs.push(n);
            x /= n;
            if x == 1 {
                return rs;
            }
        }
        n += 1;
    }
}
fn prime_factorization_ex(x: usize) -> HashMap<usize, usize> {
    let mut rs = HashMap::new();
    for n in prime_factorization(x) {
        *rs.entry(n).or_insert(0) += 1;
    }
    rs
}

fn lcm(x0: usize, x1: usize) -> usize {
    let pf0 = prime_factorization_ex(x0);
    let pf1 = prime_factorization_ex(x1);

    let keys: HashSet<_> = pf0.keys().chain(pf1.keys()).cloned().collect();
    let mut result = 1;

    for key in keys {
        let c0 = pf0.get(&key).cloned().unwrap_or(0);
        let c1 = pf1.get(&key).cloned().unwrap_or(0);
        let c = c0 + c1 - min(c0, c1);
        for _ in 0..c {
            result *= key;
        }
    }
    result
}

mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        s: String,
    }

    macro_rules! fn_read {
        { $f:ident($($t:ident),*) } => {
            #[allow(dead_code)]
            pub fn $f<$($t: FromStr),*>(&mut self) -> ($($t),*) {
                let i = &mut self.read_line().split(' ');
                ($(read_next::<$t,_>(i)),*)
            }
        };
    }

    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                s: String::new(),
            }
        }
        pub fn read_line(&mut self) -> &str {
            self.s.clear();
            self.r.read_line(&mut self.s).unwrap();
            self.s.trim()
        }

        fn_read! { read2(T1, T2) }
        fn_read! { read3(T1, T2, T3) }
        fn_read! { read4(T1, T2, T3, T4) }
        fn_read! { read5(T1, T2, T3, T4, T5) }
    }
    fn read_next<'a, T: FromStr, I: Iterator<Item = &'a str>>(i: &mut I) -> T {
        i.next().unwrap().parse().ok().unwrap()
    }
}