#include <bits/stdc++.h>
using namespace std;
template <typename T>
void rd(T &t) {
  t = 0;
  int f = 1;
  char p = getchar();
  while (p < 48 || p > 57) {
    if (p == 45) f = -1;
    p = getchar();
  }
  do {
    (t *= 10) += p - 48;
    p = getchar();
  } while (p > 47 && p < 58);
  t *= f;
}
long long m;
int a[999], d[999], vis[999];
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
void dfs(int u) {
  vis[u] = true;
  ++m;
  if (!vis[a[u]]) dfs(a[u]);
}
int main() {
  int n, i;
  long long ans = 1;
  rd(n);
  for (i = 1; i <= n; ++i) {
    rd(a[i]);
    ++d[a[i]];
  }
  for (i = 1; i <= n; ++i)
    if (d[i] != 1) {
      puts("-1");
      return 0;
    }
  for (i = 1; i <= n; ++i)
    if (!vis[i]) {
      m = 0;
      dfs(i);
      if (m % 2 == 0) m /= 2;
      ans = ans / gcd(m, ans) * m;
    }
  printf("%lld\n", ans);
  return 0;
}
