#include <bits/stdc++.h>
int64_t n;
std::vector<std::vector<int64_t>> g;
std::vector<std::vector<int64_t>> gt;
std::vector<int64_t> s;
std::vector<bool> visited;
std::vector<int64_t> tout;
std::vector<int64_t> comp;
int64_t gcd(int64_t a, int64_t b) {
  if (!b) {
    return a;
  }
  int64_t c = a % b;
  while (c != 0) {
    a = b;
    b = c;
    c = a % b;
  }
  return b;
}
void dfs1(int64_t v) {
  if (visited[v]) {
    return;
  }
  visited[v] = true;
  for (auto nei : g[v]) {
    dfs1(nei);
  }
  tout.push_back(v);
}
void dfs2(int64_t v) {
  if (visited[v]) {
    return;
  }
  comp.push_back(v);
  visited[v] = true;
  for (auto nei : gt[v]) {
    dfs2(nei);
  }
}
bool is_loop(int64_t i) {
  for (auto nei : g[i]) {
    if (nei == i) {
      return true;
    }
  }
  return false;
}
bool scc() {
  for (int64_t i = 0; i < n; i++) {
    dfs1(i);
  }
  visited.assign(n, false);
  std::reverse(tout.begin(), tout.end());
  for (int64_t i = 0; i < n; i++) {
    dfs2(tout[i]);
    if (comp.size() == 1 && !is_loop(comp[0])) {
      return false;
    }
    if (comp.size() > 1) {
      if (comp.size() % 2 == 0) {
        s.push_back(comp.size() / 2);
      } else {
        s.push_back(comp.size());
      }
    }
    comp.clear();
  }
  return true;
}
void solve() {
  std::cin >> n;
  g.resize(n);
  gt.resize(n);
  visited.resize(n, false);
  for (int64_t i = 0; i < n; i++) {
    int64_t u;
    std::cin >> u;
    g[i].push_back(u - 1);
    gt[u - 1].push_back(i);
  }
  if (!scc()) {
    std::cout << "-1" << std::endl;
    return;
  }
  if (s.size() == 1) {
    std::cout << s[0] << std::endl;
    return;
  }
  if (s.size() == 0) {
    std::cout << 1 << std::endl;
    return;
  }
  int64_t lcm = (s[1] * s[0]) / gcd(s[1], s[0]);
  for (int64_t i = 2; i < s.size(); i++) {
    if (s[i] != 1) {
      lcm = (lcm * s[i]) / gcd(lcm, s[i]);
    }
  }
  std::cout << lcm << std::endl;
}
int32_t main() {
  solve();
  return 0;
}
