#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
// Helper function to compute the Greatest Common Divisor
long long gcd(long long a, long long b) {
while (b) {
a %= b;
swap(a, b);
}
return a;
}
int main() {
// Optimize standard I/O operations for performance
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
if (!(cin >> n)) return 0;
vector<long long> a(n + 1), b(n + 1);
long long g = 0;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
g = gcd(g, a[i]);
}
for (int i = 1; i <= n; ++i) {
cin >> b[i];
}
// If the overall GCD is already 1, no operations are required.
if (g == 1) {
cout << 0 << "\n";
return 0;
}
// Extract unique prime factors of the initial overall GCD
vector<long long> primes;
long long temp = g;
for (long long i = 2; i * i <= temp; ++i) {
if (temp % i == 0) {
primes.push_back(i);
while (temp % i == 0) {
temp /= i;
}
}
}
if (temp > 1) {
primes.push_back(temp);
}
int k = primes.size();
int max_mask = 1 << k;
// dp[mask] stores the minimum cost to achieve the state represented by mask
// -1 denotes an unreachable state
vector<long long> dp(max_mask, -1);
dp[0] = 0;
for (int i = 1; i <= n; ++i) {
int mask_i = 0;
for (int j = 0; j < k; ++j) {
if (b[i] % primes[j] != 0) {
mask_i |= (1 << j);
}
}
// If this element eliminates no prime factors, skip it
if (mask_i == 0) continue;
long long cost = 1LL * i * i + i;
// Update the DP table from top to bottom to use only one array copy
for (int mask = max_mask - 1; mask >= 0; --mask) {
if (dp[mask] != -1) {
int next_mask = mask | mask_i;
if (dp[next_mask] == -1 || dp[mask] + cost < dp[next_mask]) {
dp[next_mask] = dp[mask] + cost;
}
}
}
}
// Output the minimum cost to eliminate all prime factors, or -1 if impossible
cout << dp[max_mask - 1] << "\n";
return 0;
}