#include <bits/stdc++.h>
using namespace std;
long long level[101], visited[101], len[101];
vector<long long> adjlist[101], in[101];
long long bfs(long long s) {
  level[s] = 1;
  visited[s] = 1;
  queue<long long> q;
  q.push(s);
  long long u;
  while (!q.empty()) {
    u = q.front();
    q.pop();
    for (long long i = 0; i < adjlist[u].size(); i++) {
      long long v = adjlist[u][i];
      if (visited[v] != 1) {
        visited[v] = 1;
        level[v] = level[u] + 1;
        q.push(v);
      }
    }
  }
  return level[u];
}
long long gcd(long long a, long long b) {
  if (b == 0)
    return a;
  else
    return gcd(b, a % b);
}
long long lcm(long long a, long long b) { return (a / gcd(a, b)) * b; }
int main() {
  long long n, i, u;
  scanf("%I64d", &n);
  for (i = 1; i <= n; i++) {
    scanf("%I64d", &u);
    adjlist[i].push_back(u);
    in[u].push_back(i);
  }
  long long a = 0;
  for (i = 1; i <= n; i++) {
    if (in[i].size() == 0) {
      printf("-1\n");
      return 0;
    }
    if (!visited[i]) {
      long long l = bfs(i);
      l = (l & 1) ? l : l / 2;
      len[a++] = l;
    }
  }
  long long res = accumulate(len, len + a, 1, lcm);
  cout << res << endl;
  return 0;
}
