#include #include #include using namespace atcoder; using mint = modint998244353; using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf 1000000001 int main(){ int N,M; cin>>N>>M; vector A(N),B(M); rep(i,N)cin>>A[i]; rep(i,M)cin>>B[i]; int g = gcd(N,M); int ans = Inf; rep(i,N){ rep(j,M){ if(A[i]==B[j]){ auto ret = crt({i,j},{N,M}); if(ret.second==0)continue; ans = min(ans,(int)ret.first); } } } if(ans==Inf)ans = -1; else ans++; cout<