#include long long int gcd(long long int a, long long int b) { long long int r = a % b; while (r > 0) { a = b; b = r; r = a % b; } return b; } long long int eu(long long int a, long long int b) { if (b == 1) return 0; else return (1 - b * eu(b, a % b)) / (a % b); } int main() { long long int n, m; scanf("%lld %lld", &n, &m); long long int i, j; int a[5003], b[5003]; for (i = 0; i < n; i++) scanf("%d", &a[i]); for (j = 0; j < m; j++) scanf("%d", &b[j]); long long int ans = -2, g = gcd(n, m); long long int x, y; long long int k; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { if (a[i] != b[j]) continue; if ((j - i) % g != 0) continue; x = eu(n / g, m / g); y = (1 - n / g * x) / (m / g); y *= -1; x *= (j - i) / g; y *= (j - i) / g; k = 0; if (x < 0) k = (-x + m / g - 1) / (m / g); if (y < 0) { if (k < (-y + n / g - 1) / (n / g)) k = (-y + n / g - 1) / (n / g); } x += m / g * k; y += n / g * k; if (ans<0 || ans>x * n + i) ans = x * n + i; } } printf("%lld\n", ans + 1); return 0; }