using System; using System.Collections.Generic; using static System.Console; using System.Linq; class yc299 { static int[] NList => ReadLine().Split().Select(int.Parse).ToArray(); static int[][] NMap(int n) => Enumerable.Repeat(0, n).Select(_ => NList).ToArray(); static void Main() { var c = NList; var a = NList; var b = NList; var max = a.Length * b.Length / GCD(a.Length, b.Length); for (var i = 0; i < max; ++i) { if (a[i % a.Length] == b[i % b.Length]) { WriteLine(i + 1); return; } } WriteLine(-1); } static int GCD(int a, int b) { if (a < b) return GCD(b, a); if (a % b == 0) return b; return GCD(b, a % b); } }