#include <bits/stdc++.h>
using namespace std;
const int N = 1234567;
const long long INF = 1e18;
int Next[N], rs = 1, cnt;
int c[N], impossible = 0;
long long MUL = 1;
void dfs(int in, int x) {
  if (impossible) return;
  c[x] = 1;
  if (c[Next[x]] && Next[x] != in) impossible = 1;
  if (!c[Next[x]]) cnt++, dfs(in, Next[x]);
}
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
long long bcnn(long long a, long long b) { return a * b / gcd(a, b); }
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int foo;
    cin >> foo;
    Next[i] = foo;
  }
  for (int i = 1; i <= n; i++) {
    cnt = 1;
    if (!c[i]) dfs(i, i);
    if (cnt & 1)
      rs = bcnn(rs, cnt);
    else
      rs = bcnn(rs, cnt / 2);
  }
  if (impossible)
    cout << "-1";
  else
    cout << rs;
  return 0;
}
