#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3f;
const double EPS = 1e-9;
const int maxn = (int)1e2 + 9;
int G[maxn][maxn], a[maxn], n;
long long gcd(long long a, long long b) { return a == 0 ? b : gcd(b % a, a); }
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
void Solve() {
  while (cin >> n) {
    memset(G, (0x3f), sizeof(G));
    for (int i = (1); i <= (n); i++) {
      cin >> a[i];
      G[i][a[i]] = 1;
    }
    for (int k = (1); k <= (n); k++)
      for (int i = (1); i <= (n); i++)
        for (int j = (1); j <= (n); j++) {
          G[i][j] = min(G[i][j], G[i][k] + G[k][j]);
        }
    std::vector<int> vec;
    int f = 0;
    for (int i = (1); i <= (n); i++) {
      int d = G[i][i];
      if (d == INF) {
        f = 1;
        break;
      }
      if (d % 2 == 0)
        vec.push_back(d / 2);
      else
        vec.push_back(d);
    }
    if (f) {
      cout << "-1" << endl;
    } else {
      long long ans = 1;
      for (int i = (0); i <= (int(vec.size()) - 1); i++) {
        ans = lcm(ans, vec[i]);
      }
      cout << (ans) << endl;
    }
  }
}
int main() {
  Solve();
  return 0;
}
