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

(defn gcd [A B]
  (.gcd (BigInteger. (str A)) (BigInteger. (str B))))

(defn lcm [a b]
  (quot (*' (bigint a) (bigint b)) (gcd a b)))

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

(defn second-inner [M T L X]
  (let [Number (quot L M)]
    (loop [t T i (int 0)]
      (if (empty? t)
        true
        (if-let [v (find X i)]
          (if (not= (v 1) (first t))
            false
            (recur (rest t) (unchecked-add-int i Number)))
          (recur (rest t) (unchecked-add-int i Number)))))))


(defn TwoAbbreviation [[[N M] S T]]
  (let [L (lcm N M)]
    (if (->> (first-inner N S L) (second-inner M T L))
      (int L)
      -1)))

(->> (input)
  TwoAbbreviation
  println)