#include <bits/stdc++.h>
using namespace std;
long long arr[100005], freq[100005];
long long t, n, m, x, y, a, b, c = 0, z, p, q, r, sum = 0;
vector<long long> adj[100005], v;
int vis[100005];
set<long long> s;
void init() {
  for (int i = 0; i < 500; i++) {
    vis[i] = 0;
  }
}
void dfs(int v) {
  if (vis[v] != 1) {
    vis[v]++;
    c++;
  }
  if (vis[x] == 1) return;
  for (int i = 0; i < adj[v].size(); i++) {
    if (vis[adj[v][i]] != 1) dfs(adj[v][i]);
  }
}
long long gcd(long long x, long long y) {
  if (x == 0) return y;
  return gcd(y % x, x);
}
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a;
    adj[i + 1].push_back(a);
  }
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    if (i == adj[adj[i][0]][0]) {
      ans = max(ans, 1);
    } else {
      init();
      c = 0;
      vis[i] = -1;
      x = i;
      dfs(i);
      if (vis[i] != 1) {
        cout << -1;
        return 0;
      }
      long long cc = c - 1;
      if (cc % 2 == 0) cc /= 2;
      long long g = gcd(max(ans, 1), cc);
      ans = max(1, ans) * (cc) / g;
    }
  }
  cout << ans;
  return 0;
}
