#include <bits/stdc++.h>
using namespace std;
const bool DEBUG = 1;
template <typename S, typename T>
ostream& operator<<(ostream& out, pair<S, T> const& p) {
  out << '(' << p.first << ", " << p.second << ')';
  return out;
}
template <typename T>
ostream& operator<<(ostream& out, set<T> const& v) {
  for (auto i = v.begin(); i != v.end(); i++) out << (*i) << ' ';
  return out;
}
template <typename T, typename V>
ostream& operator<<(ostream& out, map<T, V> const& v) {
  for (auto i = v.begin(); i != v.end(); i++)
    out << "\n" << (i->first) << " : " << (i->second);
  return out;
}
template <typename T, typename V>
ostream& operator<<(ostream& out, unordered_map<T, V> const& v) {
  for (auto i = v.begin(); i != v.end(); i++)
    out << "\n" << (i->first) << " : " << (i->second);
  return out;
}
template <typename T>
ostream& operator<<(ostream& out, multiset<T> const& v) {
  for (auto i = v.begin(); i != v.end(); i++) out << (*i) << ' ';
  return out;
}
template <typename T>
ostream& operator<<(ostream& out, unordered_set<T> const& v) {
  for (auto i = v.begin(); i != v.end(); i++) out << (*i) << ' ';
  return out;
}
template <typename T>
ostream& operator<<(ostream& out, unordered_multiset<T> const& v) {
  for (auto i = v.begin(); i != v.end(); i++) out << (*i) << ' ';
  return out;
}
template <typename T>
ostream& operator<<(ostream& out, vector<T> const& v) {
  long long l = v.size();
  for (long long i = 0; i < l - 1; i++) out << v[i] << ' ';
  if (l > 0) out << v[l - 1];
  return out;
}
template <typename T>
void trace(const char* name, T&& arg1) {
  cout << name << " : " << arg1 << "\n";
}
template <typename T, typename... Args>
void trace(const char* names, T&& arg1, Args&&... args) {
  const char* comma = strchr(names + 1, ',');
  cout.write(names, comma - names) << " : " << arg1 << " | ";
  trace(comma + 1, args...);
}
map<long long, long long> g;
long long dfs(long long i, long long parent, long long ans, vector<bool>& v) {
  if (i == parent) return ans;
  if (v[i]) return -1;
  v[i] = 1;
  if (g[i] == i) return -1;
  return dfs(g[i], parent, ans + 1, v);
}
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long n;
  cin >> n;
  long long ans = 1;
  for (long long i = 0; i < n; i++) {
    long long t;
    cin >> t;
    g[i] = t - 1;
  }
  for (long long i = 0; i < n; i++) {
    vector<bool> v(n);
    v[i] = 1;
    long long length = dfs(g[i], i, 1, v);
    if (length == 1) continue;
    if (length == -1) {
      ans = -1;
      break;
    }
    if (length % 2 == 0) length /= 2;
    ans = length * ans / gcd(length, ans);
  }
  cout << ans << "\n";
}
