(defn input []
  (vector
    (->> (clojure.string/split (read-line) #"\s")
      (map #(Integer/parseInt %)))
    (apply list (read-line))
    (apply list (read-line))))

(defn gcd
  [a b]
  (if (zero? b)
    a
    (recur b, (mod a b))))

(defn lcm
  [a b]
  (/ (* a b) (gcd a b)))

(defn inner [N S L]
  (zipmap (range 0 L (quot L N)) S))


(defn TwoAbbreviation [[[N M] S T]]
  (let [L (int (lcm N M))
        S' (inner N S L)
        T' (inner M T L)
        tmp (set (concat S' T'))]
    (if (every? #(= 1 (count (% 1))) (group-by first tmp))
      L
      -1)))




(->> (input)
  TwoAbbreviation
  println)