#include <bits/stdc++.h>
using namespace std;
 
#define ll long long
#define pb push_back
#define pii pair <int, int>
#define vi vector<int>

#define FOR(i, a, b) for (int i=a; i<b; i++)
#define FORd(i, a, b) for (int i=a-1; i>=b; i--)
#define F0Rd(i, a) for (int i=a-1; i>=0; i--)
#define F0R(i, a) for (int i=0; i<a; i++)
 
#define f first
#define s second
#define lb lower_bound
#define ub upper_bound
 
const int MOD = 1000000007;
long double PI = 4*atan(1);
/*std::cout << std::fixed << std::setprecision(2);
ll po (ll b, ll p) return !p?1:po(b*b%MOD,p/2)*(p&1?b:1)%MOD;
ll inv (ll b) { return po(b,MOD-2); }*/

ll n,a[50],frq[50],x,ans=1;
vi v[50];
bool visited[50];

void solve() {
	cin >> n;
	F0R(i,n) {
		cin >> x;
		FOR(j,2,50) {
			if (x%j == 0) v[i].pb(j);
			while (x%j == 0) x /= j;
		}
	}
	// F0R(i,n) {
	// 	for (int j:v[i]) cout << j << " ";
	// 	cout << "\n";
	// }
	while (1) {
		int flag = 0,MxF = 0,MxN = -1;
		F0R(i,50) frq[i] = 0;
		F0R(i,n) {
			if (visited[i]) continue;
			flag = 1;
			for (int j:v[i]) frq[j]++;
		} 
	    if (!flag) break;
	    F0R(i,50) if (frq[i] > MxF) MxF = frq[i],MxN = i;
	    ans = ans*(ll)(MxN);
	    F0R(i,n) {
	    	if (!visited[i]) {
	    		for (int j:v[i]) {
	    			if (j == MxN) visited[i] = true;
	    		}
	    	}
	    }
	}
	cout << ans;
}

int main()
{
    ios::sync_with_stdio(0), cin.tie(0);
    int test_cases = 1;
    //cin >> test_cases;
    F0R(i,test_cases) {
    	solve();
    }
    return 0;
}
#include<bits/stdc++.h>
using namespace std;
long long ans;
void noanswer() {
	puts("-1");
	exit(0);
}
int a[100005], b[100001];
struct info {
	int cnt, p;
};
info seq[100001];
int tot;
void solve(int l, int r) {
	int p = l-1;
	while (p < r && a[p+1] > b[p+1]) ++p;
	for (int i = p+1; i <= r; i++)
		if (a[i] > b[i]) noanswer();
	for (int i = l-1; i <= p; i++) {
		if (seq[tot].p + seq[tot].cnt == a[p]) ++seq[tot].cnt;
		else ++tot, seq[tot].cnt = 1, seq[tot].p = a[i];
	}
	for (int i = p; i >= l; i--) {
		int num = 0;
		while (tot > 1 && seq[tot].p + seq[tot].cnt - 1 + num > b[i]) num += seq[tot].cnt, --tot;
		if (seq[tot].p + seq[tot].cnt - 1 + num != b[i]) noanswer();
		ans += num, seq[tot].cnt += num-1;
	}
	tot = 0;
	for (int i = r+1; i > p; i--) {
		if (seq[tot].p - seq[tot].cnt == a[p]) ++seq[tot].cnt;
		else ++tot, seq[tot].cnt = 1, seq[tot].p = a[i];
	}
	for (int i = p+1; i <= r; i++) {
		int num = 0;
		while (tot > 1 && seq[tot].p - seq[tot].cnt + 1 - num < b[i]) num += seq[tot].cnt, --tot;
		if (seq[tot].p - seq[tot].cnt + 1 - num != b[i]) noanswer();
		ans += num, seq[tot].cnt += num-1;
	}
}
int main() {
	int n, l;
	cin >> n >> l;
	for (int i = 1; i <= n; i++) cin >> a[i];
	for (int i = 1; i <= n; i++) cin >> b[i];
	a[0] = 0, a[n+1] = l+1;
	int last = 1;
	for (int i = 1; i <= n; i++)
		if (a[i] == b[i]) {
			if (last != i) solve(last, i-1);
			last = i+1;
		}
	if (last <= n) solve(last, n);
	cout << ans << endl;
}