#include <atcoder/math>
#include <iostream>
#include <stdio.h>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
using namespace atcoder;
#define ll long long
#define Pll pair<ll,ll>

signed main(){
  ll N,M,K,ans=1000000000000;
  cin>>N>>M;
  vector<ll> A(N);
  vector<ll> B(M);
  vector<ll>r(2);
  vector<ll>m={N,M};
  for(ll i=0;i<N;i++)cin>>A.at(i);
  for(ll i=0;i<M;i++)cin>>B.at(i);
  for(ll i=0;i<N;i++)for(ll j=0;j<M;j++){
    if(A.at(i)==B.at(j)){    
      r.at(0)=i+1;
      r.at(1)=j+1;
      Pll a=crt(r,m);
      ans=min(ans,a.first%a.second);
    }
  }
  if(ans==1000000000000)printf("-1\n");
  else printf("%lld\n",ans);
  return 0;
}