#include <bits/stdc++.h>
using namespace std;
int a[101];
int vis[101] = {0};
int vis_pre[101] = {0};
map<int, bool> counted;
vector<int> v;
bool fail;
void bfs(int x, int len, int stage) {
  if (fail) return;
  if (vis[a[x]] != -1 && vis_pre[a[x]] != stage) {
    fail = true;
    return;
  }
  int i, j;
  vis[x] = len;
  vis_pre[x] = stage;
  if (vis[a[x]] == -1) {
    bfs(a[x], len + 1, stage);
  } else if (vis_pre[x] == vis_pre[a[x]] && vis[a[x]] != -1 && a[x] == x &&
             len == 1) {
    v.push_back(1);
    return;
  }
  if (vis[a[x]] != -1 && a[x] == x && len == vis[a[x]]) {
    fail = true;
    return;
  }
  if (vis[a[x]] != -1 && len > vis[a[x]]) {
    if ((vis[a[x]] != 1 && a[x] != x) ||
        (vis[a[x]] != -1 && a[x] == x && len > 1)) {
      fail = true;
      return;
    }
    if (len - vis[a[x]] > 1 && !counted[(len - vis[a[x]]) + 1]) {
      if ((len - vis[a[x]]) % 2 == 1) {
        v.push_back(((len - vis[a[x]]) + 1) / 2);
      } else {
        v.push_back(((len - vis[a[x]]) + 1));
      }
      counted[(len - vis[a[x]]) + 1] = 1;
    } else if (!counted[(len - vis[a[x]])] && (len - vis[a[x]]) == 1)
      v.push_back(len - vis[a[x]]), counted[(len - vis[a[x]])] = 1;
  }
}
int gcd(int x, int y) {
  while (x * y != 0) {
    if (x < y) swap(x, y);
    x = x % y;
  }
  return x + y;
}
int main() {
  int b, c, d, i, j, n, m;
  for (i = 0; i < 101; i++) {
    vis[i] = -1;
  }
  cin >> n;
  for (i = 0; i < n; i++) {
    cin >> a[i];
    a[i]--;
  }
  j = 1;
  for (i = 0; i < n; i++) {
    if (vis[i] == -1) {
      fail = false;
      bfs(i, 1, j);
      j++;
      if (fail) {
        cout << -1 << endl;
        return 0;
      }
    }
  }
  for (i = 0; i < n; i++) {
    if (vis[i] == -1) {
      cout << -1 << endl;
      return 0;
    }
  }
  if (v.size() == 0) {
    cout << -1 << endl;
    return 0;
  }
  sort(v.begin(), v.end());
  b = v[0];
  for (i = 1; i < v.size(); i++) {
    b = b * v[i] / gcd(b, v[i]);
  }
  cout << b << endl;
  return 0;
}
