As you have noticed, there are lovely girls in Arpa’s land.People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi.  Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows.The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time.Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t ≥ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible.Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i).

The first line of input contains integer n (1 ≤ n ≤ 100) — the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≤ crushi ≤ n) — the number of i-th person's crush.

If there is no t satisfying the condition, print -1. Otherwise print such smallest t.

NoteIn the first sample suppose t = 3. If the first person starts some round:The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1.The process is similar for the second and the third person.If the fourth person starts some round:The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4.In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa.

import com.sun.org.apache.xpath.internal.operations.Bool;

import java.io.*;
import java.util.*;
import java.lang.*;

public final class Main {

    private boolean isPrime(int  n){
        if(n == 1) return false;
        for (int i = 2; i <= Math.sqrt(n); i++)
            if(n % i == 0) return false;

        return true;
    }

    public static int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }

    public static int lcm(int a, int b) {
        return a / gcd(a, b) * b;
    }

    private int lcmArr(ArrayList<Integer> arr){
        int res = lcm(arr.get(0), arr.get(1));
        for (int i = 2; i < arr.size(); i++){
            res = lcm(res, arr.get(i));
        }
        return res;
    }

    public void solve() {
        int n = in.nextInt();
        ArrayList<Integer> arr = new ArrayList<Integer>();
        ArrayList<Integer> res = new ArrayList<Integer>();
        int tmp = 0, count = 0, min = 0;
        for (int i = 0; i < n; i++){
            tmp = in.nextInt() - 1;
            if (arr.contains(tmp)){
                out.print("-1");
                return;
            }
            arr.add(tmp);
        }
        for (int i = 0; i < n; i++){
            tmp = arr.get(i);
            while (tmp != i){
                count++;
                tmp = arr.get(tmp);
            }
            count++;
            if (count % 2 == 0){
                res.add(count/2);
            }else{
                res.add(count);
            }
            count = 0;
        }
        out.print(lcmArr(res));
    }

    //    -------------I/O-------------    \\
    void run() {
        try {
            in = new FScanner(new File("input.txt"));
            out = new PrintWriter(new BufferedWriter(new FileWriter(new File("output.txt"))));
            solve();
            out.close();
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    void runIO() {
        in = new FScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out));
        solve();
        out.close();
        in.close();
    }

    public static void main(String[] args) {
        new Main().runIO();
    }

    private FScanner in;
    private PrintWriter out;

    class FScanner {

        private BufferedReader br;
        private StringTokenizer st;

        public FScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
        }

        void useString(String s) {
            if (s != null) {
                st = new StringTokenizer(s);
            }
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String s = "";
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return s;
        }

        void close() {
            try {
                br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

import java.util.*;
import java.io.*;

public final class ProblemC {
    private static boolean hasVertexWithZeroInDegree(final int[] out) {
        final int[] in = new int[out.length];
        for (int to: out) {
            in[to]++;
        }
        for (int indegree: in) {
            if (indegree == 0) {
                return true;
            }
        }
        return false;
    }

    private static int cycleLength(
            final int[] out,
            final int i,
            final boolean[] visited) {
        visited[i] = true;
        int length = 1;
        for (int to = out[i]; to != i;) {
            length++;
            visited[to] = true;
            to = out[to];
        }
        return length;
    }

    private static int gcd(final int a, final int b) {
        if (a < b) {
            return gcd(b, a);
        } else if (b == 0) {
            return a;
        } else {
            return gcd(b, a % b);
        }
    }

    private static int lcm(final int a, final int b) {
        return a / gcd(a, b) * b;
    }

    public static void main(final String[] args) {
        final Scanner in = new Scanner(System.in);
        final int n = in.nextInt();
        final int[] crush = new int[n];
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
        }
        if (hasVertexWithZeroInDegree(crush)) {
            System.out.println(-1);
            return;
        }

        List<Integer> tForComponent = new ArrayList<>();
        final boolean[] visited = new boolean[n];
        for (int i = 0; i < n; i++) {
            if (visited[i]) {
                continue;
            }
            final int cycleLength = cycleLength(crush, i, visited);
            if (cycleLength % 2 == 0) {
                tForComponent.add(cycleLength / 2);
            } else {
                tForComponent.add(cycleLength);
            }
        }

        if (tForComponent.size() == 1) {
            System.out.println(tForComponent.get(0));
        } else {
            int lcm = lcm(tForComponent.get(0), tForComponent.get(1));
            for (int i = 2; i < tForComponent.size(); i++) {
                lcm = lcm(lcm, tForComponent.get(i));
            }
            System.out.println(lcm);
        }
    }
}

import java.io.*;
import java.util.*;

public class Template implements Runnable {

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException {
        try {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        } catch (Exception e) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            try {
                tok = new StringTokenizer(in.readLine(), " :");
            } catch (Exception e) {
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    int[] readIntArray(int size) throws IOException {
        int[] res = new int[size];
        for (int i = 0; i < size; i++) {
            res[i] = readInt();
        }
        return res;
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    <T> List<T>[] createGraphList(int size) {
        List<T>[] list = new List[size];
        for (int i = 0; i < size; i++) {
            list[i] = new ArrayList<>();
        }
        return list;
    }

    public static void main(String[] args) {
        new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
    }

    long timeBegin, timeEnd;

    void time() {
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    long memoryTotal, memoryFree;

    void memory() {
        memoryFree = Runtime.getRuntime().freeMemory();
        System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
                + " KB");
    }

    public void run() {
        try {
            timeBegin = System.currentTimeMillis();
            memoryTotal = Runtime.getRuntime().freeMemory();
            init();
            solve();
            out.close();
            if (System.getProperty("ONLINE_JUDGE") == null) {
                time();
                memory();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    long gcd(long a, long b) {
        return a == 0 ? b : gcd(b % a, a);
    }

    long lcm(long a, long b) {
        return a * b / gcd(a, b);
    }

    void solve() throws IOException {
        int n = readInt();
        int[] a = readIntArray(n);
        boolean[] hasIncoming = new boolean[n];
        for (int i = 0; i < n; i++) {
            int to = a[i] - 1;
            if (hasIncoming[to]) {
                out.println(-1);
                return;
            }
            hasIncoming[to] = true;
        }

        boolean[] used = new boolean[n];
        long answer = 1;
        for (int i = 0; i < n; i++) {
            if (used[i]) continue;
            int cur = i;
            int len = 1;
            while (a[cur] - 1 != i) {
                cur = a[cur] - 1;
                len++;
            }
            if (len % 2 == 0) {
                len /= 2;
            }
            answer = lcm(answer, len);
        }
        out.println(answer);

    }

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int[] crush = new int[n + 1];
            int[] crushCount = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                crush[i] = in.nextInt();
                crushCount[crush[i]]++;
            }
            for (int i = 1; i <= n; i++) {
                if (crushCount[i] != 1) {
                    out.println(-1);
                    return;
                }
            }
            boolean[] used = new boolean[n + 1];
            long lcmV = 1;
            for (int i = 1; i <= n; i++) {
                int cur = i;
                int len = 0;
                while (!used[cur]) {
                    used[cur] = true;
                    cur = crush[cur];
                    len++;
                }
                if (len > 0) {
                    int cyc = (len % 2 == 0) ? len / 2 : len;
                    lcmV = lcm(cyc, lcmV);
                }
            }
            out.println(lcmV);
        }

        long gcd(long a, long b) {
            if (b == 0) return a;
            return gcd(b, a % b);
        }

        long lcm(long a, long b) {
            return a * b / gcd(a, b);
        }

    }

    static class InputReader {
        private StringTokenizer tokenizer;
        private BufferedReader reader;

        public InputReader(InputStream inputStream) {
            reader = new BufferedReader(new InputStreamReader(inputStream));
        }

        private void fillTokenizer() {
            if (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }

        public String next() {
            fillTokenizer();
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.*;

import java.util.*;
import java.util.Map.Entry;

import javax.swing.text.InternationalFormatter;

import java.math.*;

public class template {

	public static PrintWriter out;
	static TreeMap<Long, Long> hm;
	static ArrayList<Integer>[] a;
	static boolean b = false;

	public static void main(String[] args) throws IOException {

		Reader scn = new Reader();

		int n = scn.nextInt();
		int[] p = scn.nextIntArray(n);

		a = new ArrayList[n + 1];

		for (int i = 1; i <= n; i++)
			a[i] = new ArrayList<>();

		for (int i = 0; i < p.length; i++)
			a[i + 1].add(p[i]);

		pair[] c = new pair[n + 1];

		for (int i = 0; i < c.length; i++)
			c[i] = new pair();

		for (int i = 1; i <= n; i++)
			dfs(i, new HashSet<>(), c, i);

		long ans = 1;

		for (int j = 1; j < c.length; j++) {

			pair i = c[j];

			if (i.e == Integer.MAX_VALUE && i.e == i.o) {
				System.out.println(-1);
				return;
			}

			ans = lcm(ans, Math.min(i.e, i.o));
		}

		System.out.println(ans);

	}

	public static void dfs(int v, HashSet<Integer> visited, pair[] c, int src) {

		visited.add(v);

		for (int nbr : a[v]) {
			if (!visited.contains(nbr))
				dfs(nbr, visited, c, src);

			else if (nbr == src) {

				Iterator itr = visited.iterator();

				while (itr.hasNext()) {

					int x = (int) itr.next();

					if (visited.size() % 2 == 0)
						c[x].e = Math.min(c[x].e, visited.size() / 2);

					else
						c[x].o = Math.min(c[x].o, visited.size());

				}

			}

		}

		visited.remove(v);

	}

	static long lcm(long a, long b) {
		return (a * b) / gcd(a, b);
	}

	static long gcd(long a, long b) {
		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	// _________________________TEMPLATE_____________________________________________________________

	// private static int gcd(int a, int b) {
	// if(a== 0)
	// return b;
	//
	// return gcd(b%a,a);
	// }

	// static class comp implements Comparator<pair> {
	//
	// @Override
	// public int compare(pair o1, pair o2) {
	// return o2.b - o1.b;
	// }
	//
	// }

	static class pair implements Comparable<pair> {
		int o = Integer.MAX_VALUE;
		int e = Integer.MAX_VALUE;

		// pair(int a, int b) {
		// min = a;
		// max = b;
		// }

		@Override
		public int compareTo(pair o) {

			return (int) (this.o - o.o);

		}
	}

	public static class Reader {
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;

		public Reader() {
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public Reader(String file_name) throws IOException {
			din = new DataInputStream(new FileInputStream(file_name));
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}

		public String readLine() throws IOException {
			byte[] buf = new byte[100000 + 1]; // line length
			int cnt = 0, c;
			while ((c = read()) != -1) {
				if (c == '\n')
					break;
				buf[cnt++] = (byte) c;
			}
			return new String(buf, 0, cnt);
		}

		public int nextInt() throws IOException {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}

		public long nextLong() throws IOException {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}

		public double nextDouble() throws IOException {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();

			do {
				ret = ret * 10 + c - '0';
			} while ((c = read()) >= '0' && c <= '9');

			if (c == '.') {
				while ((c = read()) >= '0' && c <= '9') {
					ret += (c - '0') / (div *= 10);
				}
			}

			if (neg)
				return -ret;
			return ret;
		}

		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}

		private byte read() throws IOException {
			if (bufferPointer == bytesRead)
				fillBuffer();
			return buffer[bufferPointer++];
		}

		public void close() throws IOException {
			if (din == null)
				return;
			din.close();
		}

		public int[] nextIntArray(int n) throws IOException {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		public long[] nextLongArray(int n) throws IOException {
			long[] arr = new long[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLong();
			}
			return arr;
		}

		public int[][] nextInt2DArray(int m, int n) throws IOException {
			int[][] arr = new int[m][n];
			for (int i = 0; i < m; i++) {
				for (int j = 0; j < n; j++)
					arr[i][j] = nextInt();
			}
			return arr;
		}

	}

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Egor Kulikov (egor@egork.net)
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.readInt();
            int[] crush = IOUtils.readIntArray(in, n);
            MiscUtils.decreaseByOne(crush);
            boolean[] processed = new boolean[n];
            BigInteger lcm = BigInteger.ONE;
            for (int i = 0; i < n; i++) {
                if (processed[i]) {
                    continue;
                }
                int count = 0;
                int current = i;
                do {
                    processed[current] = true;
                    current = crush[current];
                    count++;
                } while (!processed[current]);
                if (current != i) {
                    out.printLine(-1);
                    return;
                }
                lcm = lcm.multiply(BigInteger.valueOf(count)).divide(lcm.gcd(BigInteger.valueOf(count)));
            }
            if (lcm.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) {
                lcm = lcm.divide(BigInteger.valueOf(2));
            }
            out.printLine(lcm);
        }

    }

    static class IOUtils {
        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.readInt();
            }
            return array;
        }

    }

    static class MiscUtils {
        public static void decreaseByOne(int[]... arrays) {
            for (int[] array : arrays) {
                for (int i = 0; i < array.length; i++) {
                    array[i]--;
                }
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

        public void printLine(int i) {
            writer.println(i);
        }

    }
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        ConsoleIO io = new ConsoleIO();
        new Main(io).solve();
        io.close();
    }
    ConsoleIO io;
    Main(ConsoleIO io) {
        this.io = io;
    }

    long MOD = 1_000_000_007;
    int N, M, K, Q;

    public void solve() {
        int n = io.ri();
        int[] map = new int[n];
        for(int i = 0;i<n;i++){
            int v = io.ri()-1;
            map[i] = v;
        }

        boolean[] used = new boolean[n];
        long res = 1;
        long div = 0;
        int k = 0;

        int[] primes = new int[n+3];
        for(int i = 2;i<primes.length;i++) {
            if (primes[i] == 0) {
                for (int j = i + i; j < primes.length; j += i)
                    primes[j] = 1;
            }
        }
        int[] ps = new int[n+3];
        for(int i = 0;i<n;i++){
            if(!used[i]){
                int t = i;
                used[t] = true;
                int cur=map[i];
                int c = 1;
                while(!used[cur]){
                    c++;
                    used[cur] =true;
                    cur = map[cur];
                }
                if(cur!=t){
                    io.writeLine("-1");
                    return;
                }
                k++;
                if(c%2==0)c/=2;

                for(int j = 2;j<primes.length;j++)
                    if(primes[j]==0) {
                        int a = 0;
                        while (c % j == 0) {
                            c /= j;
                            a++;
                        }
                        ps[j] = Math.max(ps[j], a);
                    }

            }
        }

        for(int i = 0;i<ps.length;i++){
            int t = ps[i];
            while(t>0){
                res*=i;
                t--;
            }
        }

        io.writeLine(res + "");
    }

    long gcd(long a, long b) {
        if (a < b) return gcd(b, a);
        return b == 0 ? a : gcd(b, a % b);
    }

}

class ConsoleIO {
    BufferedReader br;
    PrintWriter out;
    public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);}
    public void flush(){this.out.flush();}
    public void close(){this.out.close();}
    public void writeLine(String s) {this.out.println(s);}
    public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
    public void writeWord(String s){
        this.out.print(s);
    }
    public void writeIntArray(int[] a, int k, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < k; i++) {
            if (i > 0) sb.append(separator);
            sb.append(a[i]);
        }
        this.writeLine(sb.toString());
    }
    public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
    public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
    public long[] readLongArray() {
        String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
        for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
        return r;
    }
    public int[] readIntArray() {
        String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
        for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
        return r;
    }
    public int[] readIntArray(int n) {
        int[] res = new int[n];
        char[] all = this.readLine().toCharArray();
        int cur = 0;boolean have = false;
        int k = 0;
        boolean neg = false;
        for(int i = 0;i<all.length;i++){
            if(all[i]>='0' && all[i]<='9'){
                cur = cur*10+all[i]-'0';
                have = true;
            }else if(all[i]=='-') {
                neg = true;
            }
            else if(have){
                res[k++] = neg?-cur:cur;
                cur = 0;
                have = false;
                neg = false;
            }
        }
        if(have)res[k++] = neg?-cur:cur;
        return res;
    }
    public int ri() {
        try {
            int r = 0;
            boolean start = false;
            boolean neg = false;
            while (true) {
                int c = br.read();
                if (c >= '0' && c <= '9') {
                    r = r * 10 + c - '0';
                    start = true;
                } else if (!start && c == '-') {
                    start = true;
                    neg = true;
                } else if (start || c == -1) return neg ? -r : r;
            }
        } catch (Exception ex) {
            return -1;
        }
    }
    public long readLong() {
        try {
            long r = 0;
            boolean start = false;
            boolean neg = false;
            while (true) {
                int c = br.read();
                if (c >= '0' && c <= '9') {
                    r = r * 10 + c - '0';
                    start = true;
                } else if (!start && c == '-') {
                    start = true;
                    neg = true;
                } else if (start || c == -1) return neg ? -r : r;
            }
        } catch (Exception ex) {
            return -1;
        }
    }
    public String readWord() {
        try {
            boolean start = false;
            StringBuilder sb = new StringBuilder();
            while (true) {
                int c = br.read();
                if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') {
                    sb.append((char)c);
                    start = true;
                } else if (start || c == -1) return sb.toString();
            }
        } catch (Exception ex) {
            return "";
        }
    }
    public char readSymbol() {
        try {
            while (true) {
                int c = br.read();
                if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
                    return (char) c;
                }
            }
        } catch (Exception ex) {
            return 0;
        }
    }
    public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }}
}
class Pair {
    public Pair(int a, int b) {this.a = a;this.b = b;}
    public int a;
    public int b;
}
class Tri {
    public Tri(int a, int b, int c) {this.a = a;this.b = b;this.c = c;}
    public int a;
    public int b;
    public int c;
}
class PairLL {
    public PairLL(long a, long b) {this.a = a;this.b = b;}
    public long a;
    public long b;
}

import java.io.*;
import java.util.*;
public class div383C
{
	BufferedReader in;
	PrintWriter ob;
	StringTokenizer st;
	static ArrayList<Integer> gr[];
	static ArrayList<Integer> transpose[];
	static int n;
	public static void main(String[] args) throws IOException {
		new div383C().run();
	}
	void run() throws IOException {
		//in=new BufferedReader(new FileReader("input.txt"));
		in=new BufferedReader(new InputStreamReader(System.in));
		ob=new PrintWriter(System.out);
		solve();
		ob.flush();
	}
	@SuppressWarnings("unchecked")
	void solve() throws IOException {
		n=ni();
		gr=new ArrayList[n+1];
		transpose=new ArrayList[n+1];
		for (int i=0; i<=n ;  i++ )
			{
				gr[i]=new ArrayList<Integer>();
				transpose[i]=new ArrayList<Integer>();
			}
		int degree[]=new int[n+1];
		for (int i=1; i<=n ; i++ ) {
			int v=ni();
			gr[i].add(v);
			degree[v]++;
			transpose[v].add(i);
		}
		for(int i=1 ; i<=n ; i++) {
			if(degree[i]==0)
			{
				ob.println("-1");
				return;
			}
		}
		SSCs obj=new SSCs();
		Set<Integer> s=obj.printSSC();
		long ans=1L;
		for(int i : s) {
			ans=lcm(ans,i);
		}
		ob.println(ans);
	}
	long lcm(long a , int x) {
		return (a*1L*x)/gcd(a,(long)x);
	}
	long gcd(long a , long b) {
		return b==0 ? a : gcd(b,a%b);
	}
	int ni() throws IOException {
		return Integer.parseInt(nextToken());
	}
	String nextToken() throws IOException {
		if(st==null || !st.hasMoreTokens())
			st=new StringTokenizer(in.readLine());
		return st.nextToken();
	}
}
class SSCs extends div383C {
	Stack<Integer> stk=new Stack<Integer>();
	boolean visited[];
	Set<Integer> printSSC() {
		visited=new boolean[n+1];
		for(int i=1;i<=n;i++) {
			if(!visited[i]) {
				dfs(i);
			}
		}
		Arrays.fill(visited,false);
		Set<Integer> set=new TreeSet<Integer>();
		//System.out.println("The Strongly Connected Components Are : ");
		while(!stk.isEmpty()) {
			int pop=stk.pop();
			if(visited[pop]==false) {
				int cnt=dfsutil(pop);
				if(cnt%2==1)
				set.add(cnt);
				else
				set.add(cnt/2);
			}
		}
		return set;
	}
	void dfs(int u) {
		visited[u]=true;
		for(int v : gr[u]) {
			if(!visited[v])
				{
					dfs(v);
				}
		}
		stk.push(u);
	}
	int dfsutil(int u) {
		visited[u]=true;
		//System.out.print(u+" ");
		for(int v : transpose[u])
			{
				if(!visited[v])
					return 1+dfsutil(v);
			}
		return 1;
	}
}

import java.util.*;
import java.io.*;
public class Main{
    static int cnt;
    static void dfs(int idx,int visited[],int array[],int current){
        if(visited[idx] == current && idx != current){
            cnt = -1;
            return;
        }
        if(visited[idx] == current && idx == current)return;
        ++cnt;
        visited[idx] = current;
        dfs(array[idx],visited,array,current);
    }
    static long gcd(long a,long b){
        if(a < b){
            long temp = a;
            a = b;
            b = temp;
        }
        if(b == 0)return a;
        return gcd(b,a % b);
    }
    public static void main(String [] args)throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int array[] = new int[n + 1];
        StringTokenizer st = new StringTokenizer(br.readLine());
        for(int i = 1;i <= n;i++)
            array[i] = Integer.parseInt(st.nextToken());
        int visited[] = new int[n + 1];
        ArrayList<Integer>list = new ArrayList<>();
        for(int i = 1;i <= n;i++){
            cnt = 0;
            dfs(i,visited,array,i);
            //System.out.println(cnt + " " + i);
            if(cnt == -1){
                System.out.println("-1");
                return;
            }
            int temp = (cnt & 1) == 0 ? cnt/2 : cnt;
            list.add(temp);
        }
        long ans = 1;
        for(int temp : list){
            long hcf = gcd(temp,ans);
            ans = (ans/hcf)*temp;
        }
        System.out.println(ans);
    }
}

/*
 * Remember a 6.0 student can know more than a 10.0 student.
 * Grades don't determine intelligence, they test obedience.
 * I Never Give Up.
 * I will become Candidate Master.
 * I will defeat Saurabh Anand.
 * Skills are Cheap,Passion is Priceless.
 */
import java.util.*;
import java.util.Map.Entry;
import java.io.*;

import static java.lang.System.out;
import static java.util.Arrays.*;
import static java.lang.Math.*;

public class ContestMain{
	private static Reader in=new Reader();
	private static StringBuilder ans=new StringBuilder();
	private static long MOD=1000000000+7;// 1e9+7
	private static final int N=200000+7; // 2e5+7
//    private static final double EPS=1e-9;
//    private static final int LIM=26;
//    private static final double PI=3.1415;
//    private static ArrayList<Integer> v[]=new ArrayList[N];
//    private static int color[]=new int[N];
	private static boolean mark[]=new boolean[N];

//    private static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//    private static ArrayList<Pair> v[]=new ArrayList[N];
	private static long powmod(long x,long n){
		if(n==0||x==0)
			return 1;
		else if(n%2==0)
			return(powmod((x*x)%MOD,n/2));
		else
			return (x*(powmod((x*x)%MOD,(n-1)/2)))%MOD;
	}

	private static void shuffle(long[] arr){
		for(int i=arr.length-1;i>=2;i--){
			int x=new Random().nextInt(i-1);
			long temp=arr[x];
			arr[x]=arr[i];
			arr[i]=temp;
		}
	}

    private static long gcd(long a, long b){
        if(b==0)return a;
        return gcd(b,a%b);
    }
//    private static boolean check(int x,int y){
//        if((x>=0&&x<n)&&(y>=0&&y<m)&&mat[x][y]!='X'&&!visited[x][y])return true;
//        return false;
//    }
	public static void main(String[] args) throws IOException{
		int n=in.nextInt();
		int ar[]=new int[n+1];
		for(int i=1;i<=n;i++)
			ar[i]=in.nextInt();
		int node=0;
		HashSet<Integer> set=new HashSet();
		HashSet<Integer> sizeSet=new HashSet();
		long mult=1,d=0;
		boolean flag;
		for(int i=1;i<=n;i++){
			if(!mark[i]){
				node=i;
				flag=false;
				mark[i]=true;
				while(true){
					if(set.contains(node)){
						if(node==i)flag=true;
						else flag=false;
						break;
					}
					mark[node]=true;
					set.add(node);
					node=ar[node];
				}
				if(set.size()!=1){
					if(set.size()%2==0)sizeSet.add(set.size()/2);
					else sizeSet.add(set.size());
				}
				if(!flag){out.println(-1);return;}
				set.clear();
			}
		}
		for(int a:sizeSet){
			if(d==0){
				mult=a;
				d=a;
			}
			else{
				d=gcd(a,mult);
				mult=(mult*a)/d;
			}
		}
		out.println(mult);
	}
	static class Pair<T> implements Comparable<Pair>{
		long l;
		long r;

		Pair(){
			l=0;
			r=0;
		}

		Pair(long k,long v){
			l=k;
			r=v;
		}

		@Override
		public int compareTo(Pair o){
			if(o.l!=l)
				return (int)-(l-o.l);
			else
				return (int)(r-o.r);
		}
		// Fenwick tree question comparator
//        @Override
//        public int compareTo(Pair o) {
//            if(o.r!=r)return (int) (r-o.r);
//            else return (int)(l-o.l);
//        }
	}

	static class Reader{
		BufferedReader br;
		StringTokenizer st;

		public Reader(){
			br=new BufferedReader(new InputStreamReader(System.in));
		}

		String next(){
			while(st==null||!st.hasMoreElements()){
				try{

					st=new StringTokenizer(br.readLine());
				}catch(IOException e){
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt(){
			return Integer.parseInt(next());
		}

		long nextLong(){
			return Long.parseLong(next());
		}

		double nextDouble(){
			return Double.parseDouble(next());
		}

		String nextLine(){
			String str="";
			try{
				str=br.readLine();
			}catch(IOException e){
				e.printStackTrace();
			}
			return str;
		}
	}
}

import java.io.*;
import java.util.*;
import java.lang.*;

public class Rextester{
    private int[] graph;
    private int V;
    public Rextester(int V,int[] array){
        this.V = V;
        graph = new int[V];
        for(int i=0;i<V;i++){
            graph[i]=array[i];
        }
    }

    public int findCycle(int s){
        int count=0,i=s;
        boolean[] visited = new boolean[V];
        while(true){
            if(visited[i]&&s==i){
                if(count%2==0){
                    return count/2;
                }
                return count;
            }
            else if(visited[i]&&s!=i){
                return -1;
            }
            else{
                visited[i]=true;
                i=graph[i];
                count++;
            }
        }
    }

    public long findMin(){
        int[] array = new int[10000];
        int p=0;
        for(int i=0;i<V;i++){
                int x = findCycle(i);
                if(x==-1){
                    return -1;
                }
                else{
                    array[p++]=x;
                }
        }
        return LCM(array,p);
    }

    public long LCM(int[] array,int p){
        long lcm = LCM(array[0],array[1]);
        for(int i=2;i<p;i++){
            lcm=LCM(lcm,array[i]);
        }
        return lcm;
    }

    public long LCM(long a,long b){
        long m = a*b;
        long hcf = HCF(a,b);
        return m/hcf;
    }

    public long HCF(long a,long b){
        if(a%b==0){
            return b;
        }
        return HCF(b,a%b);
    }

    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = new Integer(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());
        br.close();
        int[] array = new int[n];
        for(int i=0;i<n;i++){
            array[i]=new Integer(st.nextToken())-1;
        }
        Rextester rs = new Rextester(n,array);
        System.out.println(rs.findMin());
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class C {

	static boolean visited[];

	static int dfs(int origin , int cur)
	{
		if(visited[cur])
			return INF;
		visited[cur] = true;
		//System.out.println(origin +  " " + cur);
		if(origin == next[cur])
			return 1;
		return 1+dfs(origin , next[cur]);
	}

	static int INF = (int)(-1e9);
	static int[] next ;

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();

		next = new int[n+1];
		for(int i=1;i<=n;i++)
			next[i] = sc.nextInt();

		boolean ok = true;

		long max = -1;
		for(int i=1;i<=n;i++)
		{
			//if(i != next[i])
			{
				visited = new boolean[n+1];
				int x = dfs(i,i);
				//System.out.println(x);
				if(x  < 0)
				{
					ok = false;
					break;
				}
				else
				{
					if(x%2==0)
					{
						x/=2;
					}

					if(max == -1)
					{
						max= x;
					}
					else
					{
						max= 1l*max*x/gcd(max,x);
						/*if(max%x==0 || x%max == 0)
						{
							max = Math.max(max, x);
						}
						else
						{
							ok = false;
							break;
						}
						*/
					}
				}
			}
		}
		if(!ok)
			System.out.println(-1);
		else
			System.out.println(max);
	}

	static long gcd(long x , long y)
	{
		if(x==0)
			return y;
		return gcd(y%x,x);
	}

	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}

		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public int nextInt() throws IOException {return Integer.parseInt(next());}

		public long nextLong() throws IOException {return Long.parseLong(next());}

		public String nextLine() throws IOException {return br.readLine();}

		public double nextDouble() throws IOException
		{
			String x = next();
			StringBuilder sb = new StringBuilder("0");
			double res = 0, f = 1;
			boolean dec = false, neg = false;
			int start = 0;
			if(x.charAt(0) == '-')
			{
				neg = true;
				start++;
			}
			for(int i = start; i < x.length(); i++)
				if(x.charAt(i) == '.')
				{
					res = Long.parseLong(sb.toString());
					sb = new StringBuilder("0");
					dec = true;
				}
				else
				{
					sb.append(x.charAt(i));
					if(dec)
						f *= 10;
				}
			res += Long.parseLong(sb.toString()) / f;
			return res * (neg?-1:1);
		}

		public boolean ready() throws IOException {return br.ready();}
	}

}

import java.io.*;
import java.util.*;

public class A {

	BufferedReader br;
	PrintWriter out;
	StringTokenizer st;
	boolean eof;

	void solve() throws IOException {
		int n = nextInt();
		int[] p = new int[n];

		boolean[] hasIn = new boolean[n];

		for (int i = 0; i < n; i++) {
			p[i] = nextInt() - 1;
			hasIn[p[i]] = true;
		}

		for (boolean b : hasIn) {
			if (!b) {
				out.println(-1);
				return;
			}
		}

		long ans = 1;

		boolean[] vis = new boolean[n];
		for (int i = 0; i < n; i++) {
			if (vis[i]) {
				continue;
			}

			vis[i] = true;
			int len = 1;
			for (int j = p[i]; !vis[j]; j = p[j]) {
				vis[j] = true;
				len++;
			}

			if (len % 2 == 0) {
				len /= 2;
			}

			ans = lcm(ans, len);
		}

		out.println(ans);
	}

	long lcm(long a, long b) {
		return a / gcd(a, b) * b;
	}

	long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	A() throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		out.close();
	}

	public static void main(String[] args) throws IOException {
		new A();
	}

	String nextToken() {
		while (st == null || !st.hasMoreTokens()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch (Exception e) {
				eof = true;
				return null;
			}
		}
		return st.nextToken();
	}

	String nextString() {
		try {
			return br.readLine();
		} catch (IOException e) {
			eof = true;
			return null;
		}
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.StringTokenizer;

/**
 *
 * @author Public
 */
public class A741 {
    static int count=0;
     static int k=-1;
     public static void main(String[] args) throws Exception{
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer(br.readLine());
        int n=Integer.parseInt(st.nextToken());
     ArrayList<Integer> a=new ArrayList<Integer>();
     LinkedList ad[]=new LinkedList[n];

   boolean visited[]=new boolean[n];
   Arrays.fill(visited,false);
   StringTokenizer st1=new StringTokenizer(br.readLine());
     for(int i=0;i<n;i++){
     ad[i]=new LinkedList();
     int k=Integer.parseInt(st1.nextToken());
     if(k-1!=i)
     ad[i].add(k-1);
     }
         int t=0;

   class dfs{

       int gcd(int a, int b) {
  if (b == 0) return a;
  return gcd(b, a%b);
}
int lcm(int[] a, int n) {
  int res = 1, i;
  for (i = 0; i < n; i++) {
    res = res*a[i]/gcd(res, a[i]);
  }
  return res;
}

  void DFS(int x,boolean[] v){
      count++;
      k=x;
  v[x]=true;
  ListIterator itr= ad[x].listIterator();
  while(itr.hasNext()){
  int n=(int)itr.next();

   if(v[n]==false)
          DFS(n,v);
  }
  }
 }

     for(int i=0;i<n;i++){
      count=0;

  if(visited[i]==false){
     new dfs().DFS(i,visited);
         if((ad[k].isEmpty()) ){
             if(count==1)
             t=1;
             else{ System.out.println(-1);
    return;    }}
         else if(count==2 && (int)ad[k].getFirst()==i) {t=1;}
   else if(((int)ad[k].getFirst()!=i)){
         System.out.println(-1);
    return;
   }
   else {
   t=count;
   }
         if(t%2==0)
         a.add(t/2);
         else
             a.add(t);
  }
         }
    int ar[]=new int[a.size()];
    int l=0;
    for(Integer z:a){ar[l]=z; l++;}
     System.out.println(new dfs().lcm(ar, a.size()));
     }
}

import java.util.*;

public class A741 {

	public static void main(String[] args){

		int n;

		A741 ob=new A741();

		Scanner scan=new Scanner(System.in);

		n=scan.nextInt();

		int[] arr= new int[n];

		for(int i=0;i<n;i++){
			arr[i]=scan.nextInt();
		}

		boolean[] tv=new boolean[n];

		int i=0;
		int max=1;

		for(;i<n;i++){
			if(!tv[i]){

				ArrayList<Integer> al=new ArrayList<>();

				al.add(i+1);
				int res=0;

				while(!tv[i]){

					al.add(arr[i]);
					tv[i]=true;
					i=arr[i]-1;

				}

				if(al.get(0)==al.get(al.size()-1))
				{
					res=al.size()-1;

					if(res%2==0)
						res/=2;

					max=ob.lcm(max,res);

				}

				else {

					System.out.println("-1");
					return;
				}

			}

		}

		System.out.println(max);
	}

	int lcm(int a,int b){

		int min,max;

		if(a>b)
		{
		max=a;
		min=b;
		}
		else
		{
		max=b;
		min=a;
		}

		/*
		To find the maximum and minimum numbers, you can also use
		int max=a>b?a:b;
		int min=a<b?a:b;
		*/
		 int x,lcm=1;

		for(int i=1;i<=min;i++)
		   {
		    x=max*i; //finding multiples of the maximum number
		    if(x%min==0) //Finding the multiple of maximum number which is divisible by the minimum number.
		     {
		      lcm=x; //making the 1st multiple of maximum number as lcm, which is divisible by the minimum number
		      break; //exiting from the loop, as we don’t need anymore checking after getting the LCM
		     }
		    }
		return lcm;
}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        int n;
        int[] next;
        int[] color;
        int[] parent;
        List<Integer> sizes;
        boolean[] inCycle;

        public void solve(int testNumber, InputReader in, PrintWriter out) {

            n = in.nextInt();
            next = new int[n];
            sizes = new ArrayList<>();
            parent = new int[n];
            Arrays.fill(parent, -1);
            inCycle = new boolean[n];
            color = new int[n];
            Arrays.fill(color, -1);
            for (int i = 0; i < n; i++) {
                next[i] = in.nextInt() - 1;
            }
            for (int i = 0; i < n; i++) {
                if (color[i] == -1) {
                    dfs(i);
                }
            }
            for (int i = 0; i < n; i++) {
                if (!inCycle[i]) {
                    out.println(-1);
                    return;
                }
            }
            long p = 1;
            for (int size : sizes) {
                if (size % 2 == 0)
                    size /= 2;
                p = lcm(p, size);
            }
            out.println(p);
        }

        private long gcd(long a, long b) {
            return (b == 0) ? a : gcd(b, a % b);
        }

        private long lcm(long a, long b) {
            return a / gcd(a, b) * b;
        }

        private void dfs(int v) {
            color[v] = 0;
            if (color[next[v]] == 0) {
                cycle(v, next[v]);
            } else {
                parent[next[v]] = v;
                dfs(next[v]);
            }
            color[v] = 1;
        }

        private void cycle(int v, int root) {
            int cur = v;
            int l = 1;
            inCycle[cur] = true;
            while (cur != root) {
                l++;
                cur = parent[cur];
                inCycle[cur] = true;
            }
            sizes.add(l);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(in.readLine());
        StringTokenizer st = new StringTokenizer(in.readLine());
        int[] a = new int[n+1];
        parent = new int[n+1];
        for (int i = 0; i <= n; i++) {
            parent[i] = i;
        }
        HashSet<Integer> set = new HashSet<>();
        for (int i = 1; i <= n; i++) {
            a[i] = Integer.parseInt(st.nextToken());
            set.add(a[i]);
        }
        if (set.size() != n) {
            System.out.println("-1");
            return;
        }
        for (int i = 1; i <= n; i++) {
            union(i, a[i]);
        }
        int[] size = new int[n+1];
        for (int i = 1; i <= n; i++) {
            size[find(i)]++;
        }
        long lcm = 1;
        for (int i = 1; i <= n; i++) {
            if (i == find(i)) {
                //System.out.println(i + " size is "  + size[i]);
                if (size[i] % 2 == 0) {
                    size[i] /= 2;
                }
                lcm = LCM(lcm, size[i]);
            }
        }
        System.out.println(lcm);
    }

    static int[] parent;
    static int find(int i) {
        if (parent[i] == i) {
            return i;
        }
        int res = find(parent[i]);
        parent[i] = res;
        return res;
    }
    static void union(int i, int j) {
        parent[find(i)] = find(j);
    }

    static long GCF(long a, long b) {
        if (b == 0) return a;
        else return (GCF (b, a % b));
    }

    static long LCM(long a, long b) {
        return (a*b)/(GCF(a,b));
    }
}
/*

 */

//package codeforces;

import java.util.Scanner;

/**
 * Created by nitin.s on 07/12/16.
 */
public class MehrdadEvilPlan {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] a = new int[n];
        for(int i = 0; i < n; ++i) a[i] = in.nextInt() - 1;
        boolean[] has = new boolean[n];
        for(int i = 0; i < n; ++i) {
            if(has[a[i]]) {
                System.out.println(-1);
                return;
            }
            has[a[i]] = true;
        }
        long ans = 1;
        boolean[] was = new boolean[n];
        for(int i = 0; i < n; ++i) {
            if(was[i]) continue;
            int count = 0;
            int v = i;
            while(!was[v]) {
                was[v] = true;
                ++count;
                v = a[v];
            }
            if(count % 2 == 0) count /= 2;
            ans = MathUtils.lcm(ans, count);
        }
        System.out.println(ans);

    }

    static class MathUtils {
        public static long gcd(long a, long b) {
            if (a < 0) a = -a;
            if (b < 0) b = -b;
            while (b != 0) {
                long t = a % b;
                a = b;
                b = t;
            }
            return a;
        }

        public static long lcm(long a, long b) {
            return a / gcd(a, b) * b;
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

    static BufferedReader in;
    static PrintWriter out;
    static StringTokenizer tok;

    void solve() throws IOException {
        int n = ni();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = ni() - 1;
        }

        boolean[] used = new boolean[n];
        ArrayList<Integer> list = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            if (used[i]) continue;
            used[i] = true;

            int size = 1;
            int next = a[i];
            while (i != next) {
                if (used[next]) {
                    out.println(-1);
                    return;
                }
                used[next] = true;
                size++;
                next = a[next];
            }
            if (size % 2 == 1) {
                list.add(size);
            } else {
                list.add(size / 2);
            }
        }

        int ans = 1;
        for (int i = 0; i < list.size(); i++) {
            ans = lcm(ans, list.get(i));
        }

        out.println(ans);
    }

    int gcd(int a, int b) {
        return a == 0 ? b : gcd(b % a, a);
    }

    int lcm(int a, int b) {
        return a / gcd(a, b) * b;
    }

    String ns() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine(), " ");
        }
        return tok.nextToken();
    }

    int ni() throws IOException {
        return Integer.parseInt(ns());
    }

    long nl() throws IOException {
        return Long.parseLong(ns());
    }

    double nd() throws IOException {
        return Double.parseDouble(ns());
    }

    String[] nsa(int n) throws IOException {
        String[] res = new String[n];
        for (int i = 0; i < n; i++) {
            res[i] = ns();
        }
        return res;
    }

    int[] nia(int n) throws IOException {
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = ni();
        }
        return res;
    }

    long[] nla(int n) throws IOException {
        long[] res = new long[n];
        for (int i = 0; i < n; i++) {
            res[i] = nl();
        }
        return res;
    }

    public static void main(String[] args) throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        tok = new StringTokenizer("");
        Main main = new Main();
        main.solve();
        out.close();
    }
}

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Function;

public class C_383_div2
{
	private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
	private static StringTokenizer stringTokenizer = null;
	private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

	private static String next() throws IOException
	{
		while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens()))
		{
			stringTokenizer = new StringTokenizer(bufferedReader.readLine());
		}
		return stringTokenizer.nextToken();
	}

	public static int nextInt() throws IOException
	{
		return Integer.parseInt(next());
	}

	public static double nextDouble() throws IOException
	{
		return Double.parseDouble(next());
	}

	public static long nextLong() throws IOException
	{
		return Long.parseLong(next());
	}

	public static String nextLine() throws IOException
	{
		return bufferedReader.readLine();
	}

	public static void close()
	{
		out.close();
	}

	public static final long[] POWER2 = generatePOWER2();

	static class Array<Type> implements Iterable<Type>
	{
		private Object[] array;

		public Array(int size)
		{
			this.array = new Object[size];
		}

		public Array(int size, Type element)
		{
			this(size);
			Arrays.fill(this.array, element);
		}

		public Array(Array<Type> array, Type element)
		{
			this(array.size() + 1);
			for (int index = 0; index < array.size(); index++)
			{
				set(index, array.get(index));
			}
			set(size() - 1, element);
		}

		public Array(List<Type> list)
		{
			this(list.size());
			int index = 0;
			for (Type element : list)
			{
				set(index, element);
				index += 1;
			}
		}

		public Type get(int index)
		{
			return (Type) this.array[index];
		}

		public Array set(int index, Type value)
		{
			this.array[index] = value;
			return this;
		}

		public int size()
		{
			return this.array.length;
		}

		public List<Type> toList()
		{
			List<Type> result = new ArrayList<>();
			for (Type element : this)
			{
				result.add(element);
			}
			return result;
		}

		@Override
		public Iterator<Type> iterator()
		{
			return new Iterator<Type>()
			{
				int index = 0;

				@Override
				public boolean hasNext()
				{
					return this.index < size();
				}

				@Override
				public Type next()
				{
					Type result = Array.this.get(index);
					index += 1;
					return result;
				}
			};
		}
	}

	interface BiFunctionResult<Type0, Type1, TypeResult>
	{
		TypeResult apply(Type0 x0, Type1 x1, TypeResult x2);
	}

	static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>>
	{
		public final TypeVertex vertex0;
		public final TypeVertex vertex1;

		public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
		{
			this.vertex0 = vertex0;
			this.vertex1 = vertex1;
			this.vertex0.edges.add(getThis());
			if (bidirectional)
			{
				this.vertex1.edges.add(getThis());
			}
		}

		private TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex)
		{
			TypeVertex result;
			if (vertex0 == vertex)
			{
				result = vertex1;
			}
			else
			{
				result = vertex0;
			}
			return result;
		}

		public TypeVertex from(Vertex<TypeVertex, TypeEdge> to)
		{
			return other(to);
		}

		public TypeVertex to(Vertex<TypeVertex, TypeEdge> from)
		{
			return other(from);
		}

		public abstract TypeEdge getThis();
	}

	public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>>
	{
		public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
		{
			super(vertex0, vertex1, bidirectional);
		}

		@Override
		public EdgeDefault<TypeVertex> getThis()
		{
			return this;
		}
	}

	public static class Vertex<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>>
	{
		public final int index;
		public final List<TypeEdge> edges;

		public Vertex(int index)
		{
			this.index = index;
			this.edges = new ArrayList<>();
		}

		public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult> TypeResult depthFirstSearch(
				BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
				TypeVertex vertex,
				TypeEdge edge,
				TypeResult result,
				Array<Boolean> visited
		)
		{
			if (!visited.get(vertex.index))
			{
				visited.set(vertex.index, true);
				result = function.apply(vertex, edge, result);
				for (TypeEdge edgeNext : vertex.edges)
				{
					TypeVertex vertexNext = edge.to(vertex);
					result = depthFirstSearch(function, vertexNext, edgeNext, result, visited);
				}
			}
			return result;
		}

		public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult> TypeResult depthFirstSearch(
				Array<TypeVertex> vertices,
				int indexVertexStart,
				BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
				TypeResult result
		)
		{
			Array<Boolean> visited = new Array(vertices.size(), false);
			return depthFirstSearch(function, vertices.get(indexVertexStart), null, result, visited);
		}

		public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult> TypeResult breadthFirstSearch(
				TypeVertex vertex,
				TypeEdge edge,
				BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
				Array<Boolean> visited,
				LIFO<TypeVertex> verticesNext,
				LIFO<TypeEdge> edgesNext,
				TypeResult result
		)
		{
			if (!visited.get(vertex.index))
			{
				visited.set(vertex.index, true);
				result = function.apply(vertex, edge, result);
				for (TypeEdge edgeNext : vertex.edges)
				{
					TypeVertex vertexNext = edgeNext.to(vertex);
					if (!visited.get(vertexNext.index))
					{
						verticesNext.push(vertexNext);
						edgesNext.push(edgeNext);
					}
				}
			}
			return result;
		}

		public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult> TypeResult breadthFirstSearch(
				Array<TypeVertex> vertices,
				int indexVertexStart,
				BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
				TypeResult result
		)
		{
			Array<Boolean> visited = new Array(vertices.size(), false);
			LIFO<TypeVertex> verticesNext = new LIFO<>();
			verticesNext.push(vertices.get(indexVertexStart));
			LIFO<TypeEdge> edgesNext = new LIFO<>();
			edgesNext.push(null);
			while (!verticesNext.isEmpty())
			{
				result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result);
			}
			return result;
		}

		@Override
		public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that)
		{
			return Integer.compare(this.index, that.index);
		}
	}

	public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge>
	{
		public VertexDefault(int index)
		{
			super(index);
		}
	}

	public static class Tuple2<Type0, Type1>
	{
		public final Type0 v0;
		public final Type1 v1;

		public Tuple2(Type0 v0, Type1 v1)
		{
			this.v0 = v0;
			this.v1 = v1;
		}
	}

	public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>>
	{
		public Tuple2Comparable(Type0 v0, Type1 v1)
		{
			super(v0, v1);
		}

		@Override
		public int compareTo(Tuple2Comparable<Type0, Type1> that)
		{
			int result = this.v0.compareTo(that.v0);
			if (result == 0)
			{
				result = this.v1.compareTo(that.v1);
			}
			return result;
		}
	}

	public static class SingleLinkedList<Type>
	{
		public final Type element;
		public SingleLinkedList<Type> next;

		public SingleLinkedList(Type element, SingleLinkedList<Type> next)
		{
			this.element = element;
			this.next = next;
		}

		public void toCollection(Collection<Type> collection)
		{
			if (this.next != null)
			{
				this.next.toCollection(collection);
			}
			collection.add(this.element);
		}
	}

	public static class LIFO<Type>
	{
		public SingleLinkedList<Type> start;
		public SingleLinkedList<Type> end;

		public LIFO()
		{
			this.start = null;
			this.end = null;
		}

		public void push(Type element)
		{
			SingleLinkedList<Type> list = new SingleLinkedList<>(element, null);
			if (this.start == null)
			{
				this.start = list;
				this.end = list;
			}
			else
			{
				this.end.next = list;
				this.end = list;
			}
		}

		public Type pop()
		{
			Type result = this.start.element;
			this.start = this.start.next;
			return result;
		}

		public boolean isEmpty()
		{
			return this.start == null;
		}
	}

	public static class MapCount extends TreeMap<Long, Long>
	{
		private int size;

		public MapCount()
		{
			this.size = 0;
		}

		public MapCount(Comparator<? super Long> comparator)
		{
			super(comparator);
		}

		public long add(Long key, Long delta)
		{
			long result;
			if (delta > 0)
			{
				Long value = get(key);
				if (value == null)
				{
					value = delta;
				}
				else
				{
					value += delta;
				}
				put(key, value);
				result = delta;
			}
			else
			{
				result = 0;
			}
			this.size += result;
			return result;
		}

		public long remove(Long key, Long delta)
		{
			long result;
			if (delta > 0)
			{
				Long value = get(key) - delta;
				if (value <= 0)
				{
					result = delta + value;
					remove(key);
				}
				else
				{
					result = delta;
					put(key, value);
				}
			}
			else
			{
				result = 0;
			}
			this.size -= result;
			return result;
		}

		public int size()
		{
			return this.size;
		}
	}

	public static class MapSet<TypeKey extends Comparable<? super TypeKey>, TypeValue> extends TreeMap<TypeKey, TreeSet<TypeValue>> implements Iterable<TypeValue>
	{
		private int size;
		private Comparator<? super TypeValue> comparatorValue;

		public MapSet()
		{
			this(null);
		}

		public MapSet(Comparator<? super TypeValue> comparatorValue)
		{
			super();
			this.size = 0;
			this.comparatorValue = comparatorValue;
		}

		public TypeValue firstValue()
		{
			TypeValue result;
			Map.Entry<TypeKey, TreeSet<TypeValue>> firstEntry = firstEntry();
			if (firstEntry == null)
			{
				result = null;
			}
			else
			{
				result = firstEntry.getValue().first();
			}
			return result;
		}

		public Iterator<TypeValue> iterator()
		{
			return new Iterator<TypeValue>()
			{
				Iterator<TreeSet<TypeValue>> iteratorValues = values().iterator();
				Iterator<TypeValue> iteratorValue = null;

				@Override
				public boolean hasNext()
				{
					return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext());
				}

				@Override
				public TypeValue next()
				{
					if (iteratorValue == null || !iteratorValue.hasNext())
					{
						iteratorValue = iteratorValues.next().iterator();
					}
					return iteratorValue.next();
				}
			};
		}

		public TypeValue lastValue()
		{
			TypeValue result;
			Map.Entry<TypeKey, TreeSet<TypeValue>> lastEntry = lastEntry();
			if (lastEntry == null)
			{
				result = null;
			}
			else
			{
				result = lastEntry.getValue().last();
			}
			return result;
		}

		public boolean add(TypeKey key, TypeValue value)
		{
			TreeSet<TypeValue> set = get(key);
			if (set == null)
			{
				if (comparatorValue == null)
				{
					set = new TreeSet<>();
				}
				else
				{
					set = new TreeSet<>(comparatorValue);
				}
				put(key, set);
			}
			boolean result = set.add(value);
			if (result)
			{
				this.size += 1;
			}
			return result;
		}

		public boolean remove(TypeKey key, TypeValue value)
		{
			boolean result;
			TreeSet<TypeValue> set = get(key);
			if (set == null)
			{
				result = false;
			}
			else
			{
				result = set.remove(value);
				if (set.size() == 0)
				{
					remove(key);
				}
				if (result)
				{
					this.size -= 1;
				}
			}
			return result;
		}

		@Override
		public int size()
		{
			return this.size;
		}
	}

	public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end)
	{
		int result;
		if (start == end)
		{
			result = end;
		}
		else
		{
			int middle = start + (end - start) / 2;
			if (filter.apply(middle))
			{
				result = binarySearchMinimum(filter, start, middle);
			}
			else
			{
				result = binarySearchMinimum(filter, middle + 1, end);
			}
		}
		return result;
	}

	public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end)
	{
		return -binarySearchMinimum(x -> filter.apply(-x), -end, -start);
	}

	public static long divideCeil(long x, long y)
	{
		return (x + y - 1) / y;
	}

	public static long faculty(int n)
	{
		long result = 1;
		for (int index = 2; index <= n; index++)
		{
			result *= index;
		}
		return result;
	}

	public static long[] generatePOWER2()
	{
		long[] result = new long[63];
		for (int x = 0; x < result.length; x++)
		{
			result[x] = 1L << x;
		}
		return result;
	}

	public static <T> List<T> permutation(long p, List<T> x)
	{
		List<T> copy = new ArrayList<>();
		for (int index = 0; index < x.size(); index++)
		{
			copy.add(x.get(index));
		}
		List<T> result = new ArrayList<>();
		for (int indexTo = 0; indexTo < x.size(); indexTo++)
		{
			int indexFrom = (int) p % copy.size();
			p = p / copy.size();
			result.add(copy.remove(indexFrom));
		}
		return result;
	}

	public static <Type> void println(Iterator<Type> iterator)
	{
		if (iterator.hasNext())
		{
			out.print(iterator.next());
		}
		while (iterator.hasNext())
		{
			out.print(" " + iterator.next());
		}
		out.println();
	}

	public static <Type> void println(Iterable<Type> iterable)
	{
		println(iterable.iterator());
	}

	public static void main(String[] args)
	{
		try
		{
			solve();
		} catch (IOException exception)
		{
			exception.printStackTrace();
		}
		close();
	}

	public static int cycle(int[] crush, int x)
	{
		int result = -1;
		int joon = x;
		for (int index = 0; result == -1 && index < crush.length; index++)
		{
			joon = crush[joon];
			if (joon == x)
			{
				result = index + 1;
			}
		}
		if (result > 0 && result % 2 == 0)
		{
			result /= 2;
		}
		return result;
	}

	public static int gcd(int a, int b)
	{
		int result = 1;
		int min = Math.min(a, b);
		int max = Math.max(a, b);
		for (int test = 2; result == 1 && test <= min; test++)
		{
			if (min % test == 0 && max % test == 0)
			{
				result *= test * gcd(min / test, max / test);
			}
		}
		return result;
	}

	public static int lcm(int a, int b)
	{
		return a * b / gcd(a, b);
	}

	public static int solve(int[] crush)
	{
		int result;
		Set<Integer> cycles = new TreeSet<>();
		for (int x = 0; cycles != null && x < crush.length; x++)
		{
			int cycle = cycle(crush, x);
			if (cycle == -1)
			{
				cycles = null;
			}
			else
			{
				cycles.add(cycle);
			}
		}
		if (cycles == null)
		{
			result = -1;
		}
		else
		{
			result = 1;
			for (int cycle: cycles)
			{
				result = lcm(result, cycle);
			}
		}
		return result;
	}

	public static void solve() throws IOException
	{
		int n = nextInt();
		int[] crush = new int[n];
		for (int x = 0; x < n; x++)
		{
			crush[x] = nextInt() - 1;
		}
		out.println(solve(crush));
	}
}

import java.util.*;

public class arpa_loud_owf
{
    static int n;

    static int[] c;

    static boolean[] ind;

    public static void main( String[] args )
    {
        Scanner in = new Scanner( System.in );
        n = in.nextInt();
        c = new int[n + 1];
        ind = new boolean[n + 1];
        for ( int i = 1; i <= n; i++ )
        {
            int cr = in.nextInt();
            c[i] = cr;
            ind[cr] = true;
        }
        if ( nind() )
            System.out.println( -1 );
        else
        {
            boolean[] v = new boolean[n + 1];
            int lcm = 1;
            for ( int i = 1; i <= n; i++ )
                if ( !v[i] )
                {
                    int vr = v( i );
                    if ( vr % 2 == 0 )
                        vr /= 2;
                    lcm = lcm( lcm, vr );
                }
            System.out.println( lcm );
        }
        in.close();
        System.exit( 0 );
    }

    public static int lcm( int a, int b )
    {
        for ( int i = 1; i < b; i++ )
            if ( a * i % b == 0 )
                return a * i;
        return a * b;
    }

    public static int v( int i )
    {
        int cnt = 1, tmp = c[i];
        while ( tmp != i )
        {
            cnt++;
            tmp = c[tmp];
        }
        return cnt;
    }

    public static boolean nind()
    {
        for ( int i = 1; i <= n; i++ )
            if ( !ind[i] )
                return true;
        return false;
    }
}

import java.io.*;
import java.util.*;
import java.math.*;

public class C {
    public static void main(String args[]) {
        try {
            InputReader in = new InputReader(System.in);
            int n = in.readInt();
            int ar[] = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                ar[i] = in.readInt();
            }
            boolean found[] = new boolean[n + 1];
            for (int i = 1; i < n + 1; i++) {
                found[ar[i]] = true;
            }
            for (int i = 1; i < n + 1; i++) {
                if (!found[i]) {
                    System.out.println(-1);
                    return;
                }
            }
            boolean vis[] = new boolean[n + 1];
            Vector<Integer> posans = new Vector<Integer>();
            for (int i = 1; i <= n; i++) {
                if (!vis[i]) {
                    int ti = 1;
                    int next = ar[i];
                    vis[i] = true;
                    vis[next] = true;
                    while(next != i) {
                        ti++;
                        next = ar[next];
                        vis[next] = true;
                    }
                    if (ti % 2 == 0) {
                        ti /= 2;
                    }
                    posans.add(ti);
                }
            }
            //lcm of posans vector is our answer
            int ans = posans.get(0);
            for (int i = 1; i < posans.size(); i++) {
                ans = (ans * posans.get(i)) / gcd(ans, posans.get(i));
            }
            System.out.println(ans);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static int gcd(int a, int b){
        if (a == 0 || b == 0) {
            return a + b;
        }
        return gcd(b, a % b);
    }
}
class InputReader {
    private boolean finished = false;

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int peek() {
        if (numChars == -1)
            return -1;
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                return -1;
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString() {
        int length = readInt();
        if (length < 0)
            return null;
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++)
            bytes[i] = (byte) read();
        try {
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return new String(bytes);
        }
    }

    public static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    private String readLine0() {
        StringBuffer buf = new StringBuffer();
        int c = read();
        while (c != '\n' && c != -1) {
            if (c != '\r')
                buf.appendCodePoint(c);
            c = read();
        }
        return buf.toString();
    }

    public String readLine() {
        String s = readLine0();
        while (s.trim().length() == 0)
            s = readLine0();
        return s;
    }

    public String readLine(boolean ignoreEmptyLines) {
        if (ignoreEmptyLines)
            return readLine();
        else
            return readLine0();
    }

    public BigInteger readBigInteger() {
        try {
            return new BigInteger(readString());
        } catch (NumberFormatException e) {
            throw new InputMismatchException();
        }
    }

    public char readCharacter() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        return (char) c;
    }

    public double readDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, readInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, readInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }

    public boolean isExhausted() {
        int value;
        while (isSpaceChar(value = peek()) && value != -1)
            read();
        return value == -1;
    }

    public String next() {
        return readString();
    }

    public boolean readBoolean() {
        return readInt() == 1;
    }
}

import java.util.*;
import java.math.BigInteger;

public class com {

	public static int prime[];
	public static boolean g[];
	public static int hs[];
	public static int a[];
	public static int nprime;

	public static void InitPrime() {
		for(int i = 2;  i <= 100;  i++) g[i] = true;
		nprime = 0;
		for(int i = 2;  i <= 100;  i++) if (g[i]) {
			int t = i * 2;
			while (t <= 100) {
				g[t] = false;
				t += i;
			}
			prime[++nprime] = i;
		}
	}

	public static void update(int value) {
		for(int i = 1;  i <= nprime;  i++) {
			int p = prime[i], s = 0;
			while (value % p == 0) {
				value /= p;  s++;
			}
			if (s > hs[i]) hs[i] = s;
		}
	}

	public static void main(String[] args) {
		prime = new int[222];
		a = new int[222];
		g = new boolean[222];
		hs = new int[222];

		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		for(int i = 1;  i <= n;  i++) {
			a[i] = sc.nextInt();
		}

		InitPrime();

		for(int i = 1;  i <= n;  i++) hs[i] = 0;
		for(int i = 1;  i <= n;  i++) g[i] = true;
		for(int i = 1;  i <= n;  i++) if (g[i]) {
			int x = i, first = i, ncount = 0;
			while (g[x]) {
				g[x] = false;
				x = a[x];
				ncount++;
			}
			if (x != first) {
				System.out.println(-1);
				return;
			}

			if (ncount % 2 == 0) ncount /= 2;
			update(ncount);
		}

		BigInteger ans = BigInteger.ONE;
		for(int i = 1;  i <= nprime;  i++) {
			for(int j = 1;  j <= hs[i];  j++) {
				ans = ans.multiply(BigInteger.valueOf(prime[i]));
			}
		}
		System.out.println(ans);
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigInteger;
import java.util.*;

public class C {
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();

        int n = sc.nextInt();
        int[] arr = new int[n];
        arr = sc.readIntArray(n);
        for(int a = 0; a < n; a++){
        	arr[a]--;
        }
        ArrayList<Integer> cycleLengths = new ArrayList<Integer>();
        for(int a = 0; a < n; a++){
        	int i = getCycleLength(a, arr);
        	if(i > 500){
        		System.out.println(-1);
        		System.exit(0);
        	}
        	cycleLengths.add(i);
        }
        BigInteger lcm = bigLCM(cycleLengths);
        if(lcm.mod(BigInteger.valueOf(2)).equals(BigInteger.valueOf(1))){
        	System.out.println(lcm);
        }
        else{
        	System.out.println(lcm.divide(BigInteger.valueOf(2)));
        }
    }

    private static BigInteger bigLCM(ArrayList<Integer> cycleLengths) {
		// TODO Auto-generated method stub
    	BigInteger start = BigInteger.ONE;
    	for(Integer i:cycleLengths){
    		BigInteger gcd = start.gcd(BigInteger.valueOf(i));
    		start = start.multiply(BigInteger.valueOf(i)).divide(gcd);
    	}
		return start;
	}

	private static int getCycleLength(int a, int[] arr) {
		int start = a;
		int count = 1;
		int next = arr[start];
		while(start != next && count < 501){
			next = arr[next];
			count++;
		}
		// TODO Auto-generated method stub
		return count;
	}

	public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;
        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }
        public FastScanner() {
            this(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }
        long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextLong();
            }
            return a;
        }
    }
}

/*
Keep solving problems.
*/

import java.util.*;
import java.io.*;

public class CFA {

    BufferedReader br;
    PrintWriter out;
    StringTokenizer st;
    boolean eof;
    final long MOD = 1000L * 1000L * 1000L + 7;
    int[] dx = {0, -1, 0, 1};
    int[] dy = {1, 0, -1, 0};

    int[] arr;
    boolean[] vis;
    int[] cnt;
    void solve() throws IOException {
        int n = nextInt();
        arr = nextIntArr(n);
        int[] degree = new int[n];
        for (int i = 0; i < n; i++) {
            degree[arr[i] - 1]++;
        }
        for (int i = 0; i < n; i++) {
            if (degree[i] == 0) {
                out(-1);
                return;
            }
        }

        long res = 1;
        vis = new boolean[n];
        cnt = new int[n];
        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                dfs(i, i);
                if (cnt[i] % 2 == 0) {
                    res = lcm(res, cnt[i] / 2);
                }
                else {
                    res = lcm(res, cnt[i]);
                }
            }
        }

        out(res);
    }

    void dfs(int cur, int root) {
        if (!vis[cur]) {
            vis[cur] = true;
            cnt[root]++;
            dfs(arr[cur] - 1, root);
        }
    }

    void shuffle(long[] a) {
        int n = a.length;
        for(int i = 0; i < n; i++) {
            int r = i + (int) (Math.random() * (n - i));
            long tmp = a[i];
            a[i] = a[r];
            a[r] = tmp;
        }
    }

    long lcm(long a, long b) {
        long g = gcd(a, b);
        return a * b / g;
    }

    long gcd(long a, long b) {
        while(a != 0 && b != 0) {
            long c = b;
            b = a % b;
            a = c;
        }
        return a + b;
    }

    private void outln(Object o) {
        out.println(o);
    }
    private void out(Object o) {
        out.print(o);
    }
    public CFA() throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }
    public static void main(String[] args) throws IOException {
        new CFA();
    }

    public long[] nextLongArr(int n) throws IOException{
        long[] res = new long[n];
        for(int i = 0; i < n; i++)
            res[i] = nextLong();
        return res;
    }
    public int[] nextIntArr(int n) throws IOException {
        int[] res = new int[n];
        for(int i = 0; i < n; i++)
            res[i] = nextInt();
        return res;
    }
    public String nextToken() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (Exception e) {
                eof = true;
                return null;
            }
        }
        return st.nextToken();
    }
    public String nextString() {
        try {
            return br.readLine();
        } catch (IOException e) {
            eof = true;
            return null;
        }
    }
    public int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }
    public long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }
    public double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
}

import java.util.*;

public class M{
    static Scanner sc;
    public static void swap(long a, long b){
		long tmp = a;
		a = b;
		b = tmp;
	}
    public static long gcd(long a,long b)
    {
	    if(b>a)
		    swap(a,b);
        long c;
	    while(b>0)
	    {
		    c=a%b;	a=b;	b=c;
	    }
	    return a;
    }

    public static void main(String []args){
        sc = new Scanner(System.in);
        int n=sc.nextInt();
        int num=1;
        int []a=new int[n+1];
        int []b=new int[n+1];
        while (sc.hasNext()){
            a[num]=sc.nextInt();
            num++;
        }
        long ans=1;
		int flag=0;
		for(int i=1;i<=n;++i)
		{
			if(b[i]==1)
				continue;
			long temp=1;
			int y=a[i];
			b[i]=1;
			while(y!=i){
				b[y]=1;
				y=a[y];
				temp++;
				if(temp>n){
					flag=1;
					break;
				}
			}
			if(flag==1)
				break;
			if(temp%2==0)
				temp/=2;
			ans = ans/gcd(ans,temp)*temp;
		}
		if(flag==1)
			System.out.print("-1\n");
		else System.out.print(ans);
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int crushes[] = in.readIntArray(n);
            for (int i = 0; i < crushes.length; i++) {
                crushes[i] -= 1;
            }

            Set<Integer> count = new HashSet<>();

            for (int i = 0; i < n; i++) {
                if (!checkCycle(i, crushes[i], crushes, new boolean[n])) {
                    out.println(-1);
                    return;
                } else {
                    int ct = count(i, crushes, new boolean[n]);
                    count.add(ct % 2 == 0 ? ct / 2 : ct);
                }
            }

            long lcm = 1;
            for (int ct : count) {
                long c = ct;
                lcm = MathUtils.lcm(lcm, c);
            }
            out.println(lcm);

        }

        private boolean checkCycle(int st, int current, int crushes[], boolean v[]) {
            if (st == current) {
                return true;
            } else {
                v[current] = true;
                if (!v[crushes[current]]) {
                    return checkCycle(st, crushes[current], crushes, v);
                } else {
                    return false;
                }
            }
        }

        private int count(int st, int crushes[], boolean visited[]) {
            if (visited[st]) {
                return 0;
            }
            visited[st] = true;

            return count(crushes[st], crushes, visited) + 1;

        }

    }

    static class MathUtils {
        public static long gcd(long a, long b) {
            while (b != 0) {
                long r = a % b;
                a = b;
                b = r;
            }
            return a;
        }

        public static long lcm(long a, long b) {
            return (a * b) / gcd(a, b);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        private boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public int[] readIntArray(int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++)
                array[i] = readInt();
            return array;
        }

        public int nextInt() {
            return readInt();
        }

    }
}

import java.io.*;
import java.util.*;
public class C {

	public static void main(String[] args) throws Exception{
		BufferedReader f = new BufferedReader(new InputStreamReader(System.in));

		int n = Integer.parseInt(f.readLine());
		StringTokenizer st = new StringTokenizer(f.readLine());
		int[] next = new int[n];

		for(int i = 0;i<n;i++){
			next[i] = Integer.parseInt(st.nextToken())-1;
		}
		ArrayList<Long> cycles = new ArrayList<Long>();
		boolean[] vis = new boolean[n];
		for(int i = 0;i<n;i++){
			if(vis[i]) continue;
			ArrayList<Integer> ele = new ArrayList<Integer>();
			int curr = i;
			ele.add(i);
			vis[i] = true;
			while(true){
				curr = next[curr];
				if(ele.contains(curr) && curr != i){
					System.out.println(-1);
					System.exit(0);
				}
				if(ele.contains(curr)) break;
				vis[curr] = true;
				ele.add(curr);
			}
			if(ele.size()%2 == 0) cycles.add((long) (ele.size()/2));
			else cycles.add((long) ele.size());
		}
		long gcf = cycles.get(0);
		for(int i = 1;i<cycles.size();i++){
			gcf = gcf*cycles.get(i)/gcd(gcf, cycles.get(i));
		}
		System.out.println(gcf);
	}

	public static long gcd(long a, long b){
		if(a<b){
			long temp = a;
			a = b;
			b = temp;
		}
		if(b == 0) return a;
		while(true){
			a -= b;
			if(a-b<0) break;
		}
		return gcd(a,b);
	}

}

import java.util.*;
import java.io.*;

public class ggg {

	private static InputStream stream;
	private static byte[] buf = new byte[1024];
	private static int curChar;
	private static int numChars;
	private static SpaceCharFilter filter;
	private static PrintWriter pw;

	private static void soln(){
		int n=nextInt();
		int[] arr=new int[n];
		for(int i=0;i<n;i++)
			arr[i]=nextInt();
		long lcm=1;
		int flag=0;
		for(int i=0;i<n;i++){
			int[] visited=new int[n];
			int k=arr[i];
			visited[i]=1;
			long t=1;
			while(k!=(i+1)){
				t++;
				if(k==arr[k-1] || visited[k-1]==1){
					flag=1;
					t=1;
					break;
				}
				visited[k-1]=1;
				k=arr[k-1];
			}
			if(t%2==0)
				t=t/2;
			//System.out.println(t+" "+(i+1));
			lcm=lcm(lcm,t);
		}
		if(flag!=1)
			pw.println(lcm);
		else
			pw.println(-1);
	}
	private static long gcd(long a,long b){
		if(b==0)
			return a;
		else return gcd(b,a%b);
	}
	private static long lcm(long a,long b){
		return (a*b)/gcd(a,b);
	}
	private static int min(int a,int b){
		if(a>b)
			return b;
		else
			return a;
	}
	private static class Pair implements Comparable<Pair>{
		int x;
		int y;
		public Pair(int a,int b){
			x=a;
			y=b;
		}
		@Override
		public int compareTo(Pair arg0) {
			if(this.x > arg0.x)
				return 1;
			return 0;
		}
	}
	static long pow(int a, long b, int MOD) {
		long x = 1, y = a;
		    while(b > 0) {
		        if(b%2 == 1) {
		            x=(x*y);
		            if(x>MOD) x%=MOD;
		        }
		        y = (y*y);
		        if(y>MOD) y%=MOD;
		        b /= 2;
		    }
		    return x;
		}

		static long modInverse(int a,long b, int m) {
			//pw.println((m-2)*b);
		    return pow(a,(m-2)*b,m);
		}
	private static void computeLpsArray(String pat,int size,int[] lps){
		int len=0;
		int i=1;
		lps[0]=0;
		while(i<size){
			if(pat.charAt(i)==pat.charAt(len)){
				len++;
				lps[i]=len;
				i++;
			}else{
				if(len!=0){
					len=lps[len-1];
				}else{
					lps[i]=len;
					i++;
				}
			}
		}
	}
	private static int KMP(String pat,String txt){
		int m=pat.length();
		int n=txt.length();
		int[] lps=new int[m];
		int j=0;
		int len=0;
		int index=0;
		computeLpsArray(pat,m,lps);
		int i=0;
		while(i<n){
			if(pat.charAt(j)==txt.charAt(i)){
				i++;
				j++;
			}else{
				if(j!=0)
					j=lps[j-1];
				else
					i++;
			}
			if(len<j){
				len=j;
				//pw.println(i);
				index=i;
			}
		}
		return index-len;
	}
	private static int max(int a,int b){
		if(a>b)
			return a;
		return b;
	}
	public static void main(String[] args) {
		InputReader(System.in);
		pw = new PrintWriter(System.out);
		soln();
		pw.close();
	}

	// To Get Input
	// Some Buffer Methods

	public static void InputReader(InputStream stream1) {
		stream = stream1;
	}

	private static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private static boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}

	private static int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	private static int nextInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	private static long nextLong() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	private static String nextToken() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	private static String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	private static int[] nextIntArray(int n) {
		int[] arr = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = nextInt();
		}
		return arr;
	}

	private static long[] nextLongArray(int n) {
		long[] arr = new long[n];
		for (int i = 0; i < n; i++) {
			arr[i] = nextLong();
		}
		return arr;
	}

	private static void pArray(int[] arr) {
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
		return;
	}

	private static void pArray(long[] arr) {
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
		return;
	}

	private static boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}

	private interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}

}

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;

import java.util.*;

public class random_num {
public static long x,y,d;
public static int mod= (int) (Math.pow(10,9)+7);
	public static void main(String args[]){
		InputReader s= new InputReader(System.in);
		OutputStream outputStream= System.out;
		PrintWriter out= new PrintWriter(outputStream);
		int n = s.nextInt();
        int c[] = new int[n];
        for (int i = 0; i < n; i++) {
            c[i] = s.nextInt();
        }
        boolean v[] = new boolean[n];
        for(int i=0;i<n;i++){
        	v[i]=false;
        }
        HashSet<Integer> h = new HashSet<>();
        for (int i = 0; i < n; i++) {
            if (!v[i]) {
                int count = 1;
                int curr = c[i] - 1;
                while (curr != i && !v[curr]) {
                    v[curr] = true;
                    count++;
                    curr = c[curr] - 1;
                }
                if (curr == i) {
                    if (count % 2 == 0) {
                        h.add(count / 2);
                    } else {
                        h.add(count);
                    }
                } else {
                    System.out.println(-1);
                    return;
                }
            }
        }
        if (h.isEmpty()) {
            System.out.println(-1);
            return;
        }
        int lcm=1;
        for(int i:h){
        	lcm = i*lcm/gcd(i,lcm);
        }

        System.out.println(lcm);
		out.close();
	}
	static class InputReader {

	    public BufferedReader reader;
	    public StringTokenizer tokenizer;

	    public InputReader(InputStream inputstream) {
	      reader = new BufferedReader(new InputStreamReader(inputstream));
	      tokenizer = null;
	    }

	    public String nextLine(){
	    	String fullLine=null;
	    	while (tokenizer == null || !tokenizer.hasMoreTokens()) {
	            try {
	              fullLine=reader.readLine();
	            } catch (IOException e) {
	              throw new RuntimeException(e);
	            }
	            return fullLine;
	          }
	          return fullLine;
	    }
		public String next() {
	      while (tokenizer == null || !tokenizer.hasMoreTokens()) {
	        try {
	          tokenizer = new StringTokenizer(reader.readLine());
	        } catch (IOException e) {
	          throw new RuntimeException(e);
	        }
	      }
	      return tokenizer.nextToken();
	    }
		public long nextLong() {
		      return Long.parseLong(next());
		    }
	    public int nextInt() {
	      return Integer.parseInt(next());
	    }
	  }

	public static HashMap<Integer,Long> getcatalan(int n){
		HashMap<Integer,Long> a=new HashMap<Integer,Long>();
		a.put(0,(long)1);
		for(int i=1;i<=n+1;i++){
			long m=2*(2*i-1);
			long m1=m*a.get(i-1);
			long m3=m1/(i+1);
			//out.println(m+" "+m1+" "+m2+" "+m3);

			a.put(i,m3%1000000007);
		}
		return a;
	}

	public static int getGdc(int[] x) {
	    // get the smallest of all number no need to check for higher values
	    int smallest = getSmallest(x);

	    for(int i = smallest; i >= 1; i--) {
	       int j;
	       for(j = 0; j < x.length; ++j) {
	           if(x[j] % i != 0)
	               break;
	       }
	       // if we pass through the array with all % == 0 return the value
	       if(j == x.length)
	           return i;
	    }
	    // so the only possible is 1
	    return 1;
	}

	// return smallest number of an array of int
	public static int getSmallest(int[] x) {
	    int smallest = x[0];
	    for(int i = 1; i < x.length; ++i) {
	        if(x[i] < smallest)
	            smallest = x[i];
	    }
	    return smallest;
	}
	public static int gcd(int number1, int number2) {
		if(number2 == 0){
			return number1;
		}
		return gcd(number2, number1%number2);
	}

	public static void extendedEuclidean(long a,long b){
		if(b == 0) {
	        d = a;
	        x = 1;
	        y = 0;
	    }
	    else {
	        extendedEuclidean(b, a%b);
	        long temp = x;
	        x = y;
	        y = temp - (a/b)*y;
	    }
	}

	public static int combinations(int n,int r){
		if(n==r) return 1;
		if(r==1) return n;
		if(r==0) return 1;
		return combinations(n-1,r)+ combinations(n-1,r-1);
	}
	public static long binomialCoeff(int n, int k)
	{
	    long C[][]= new long[n+1][k+1];
	    int i, j;

	    // Caculate value of Binomial Coefficient in bottom up manner
	    for (i = 0; i <= n; i++)
	    {
	        for (j = 0; j <= Math.min(i, k); j++)
	        {
	            // Base Cases
	            if (j == 0 || j == i)
	                C[i][j] = 1;

	            // Calculate value using previosly stored values
	            else
	                C[i][j] = C[i-1][j-1] + C[i-1][j];
	        }
	    }

	    return C[n][k];
	}
	public static long expo(long a, long b){
	    if (b==1)
	        return a%mod;
	    if (b==2)
	        return (a%mod)*(a%mod);

	    if (b%2==0){
	            return expo(expo(a%mod,(b%mod)/2),2);
	    }
	    else{
	        return a*(expo(expo(a%mod,((b%mod-1%mod)%mod)/2),2));
	    }
	}

	public static int[] sieve(int N){
		int arr[]= new int[N+1];
		int b[]=new int[N+1];
		for(int i=2;i<Math.sqrt(N);i++){
			if(arr[i]==0){

				for(int j= i*i;j<= N;j= j+i){
					arr[j]=1;
				}
			}
		}
		return arr;
		// All the i for which arr[i]==0 are prime numbers.
	}
	static class Pair implements Comparable<Pair>
    {
        int f,s;
        Pair(int ii, int cc)
        {
            f=ii;
            s=cc;
        }

        public int compareTo(Pair o)
        {
            return Integer.compare(this.f, o.f);
        }

    }
	public static class company{
		public int t;
		public int d;
		public company(int m,int f){
			this.t=m;
			this.d=f;
		}
		public int get_t(){
			return this.t;
		}
		public int get_d(){
			return this.d;
		}
	}
	public static class pair_comparator implements Comparator<company>{

		@Override
		public int compare(company arg0, company arg1) {
			// TODO Auto-generated method stub
			return arg0.t-arg1.t;
		}

	}

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int N = in.nextInt();
            int[] next = new int[N];
            for (int i = 0; i < N; i++) {
                next[i] = in.nextInt() - 1;
            }
            boolean[] seen = new boolean[N];
            long[] l = new long[N];
            Arrays.fill(l, 1);
            for (int i = 0; i < N; i++) {
                if (!seen[i]) {
                    int cur = i;
                    int a = 0;
                    while (!seen[cur]) {
                        seen[cur] = true;
                        cur = next[cur];
                        a++;
                    }
                    if (cur == i) {
                        if (a % 2 == 0) {
                            l[i] = a / 2;
                        } else {
                            l[i] = a;
                        }
                    } else {
                        out.println(-1);
                        return;
                    }
                }
            }
            long res = l[0];
            for (int i = 1; i < N; i++) {
                res = (l[i] * res) / MathUtils.gcd(res, l[i]);
            }
            out.println(res);
        }

    }

    static class MathUtils {
        public static long gcd(long a, long b) {
            if (a == 0) {
                return b;
            }
            return gcd(b % a, a);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

/**
 * DA-IICT
 * Author : Savaliya Sagar.
 */

import java.io.*;
import java.math.*;
import java.util.*;

public class C742 {
    public static int mod = 1000000007;
    static FasterScanner in = new FasterScanner();
    static PrintWriter o = new PrintWriter(System.out);
    public static boolean visited[];
    public static void main(String[] args) {

        int n = in.nextInt();
        int a[] = in.nextIntArray(n,1);
        if(n==1){
            o.print(1);
            o.flush();
            return;
        }
        visited = new boolean[n+1];
        long mint = -1;
        int flag = 0;
        for(int i=1;i<=n;i++){
            if(!visited[i]){
                ArrayList<Integer> c = new ArrayList<>();
               int idx = dfs(a,i,c);
               // o.println("++"+idx);
                if(idx==-1){
                    flag = 1;
                    break;
                }
                int t = c.size() - idx;
                if(t%2==0)
                    t=t/2;
              //  o.println(t);
                if(mint==-1)
                    mint = t;
                else{
                    mint = (t*mint)/gcd(t,mint);
                  //  o.println(mint);
                }
            }
        }
        if(flag==1)
            o.print(-1);
        else
            o.print(mint);
        o.close();
    }

    public static int dfs(int a[],int current,ArrayList<Integer>c){
        visited[current] = true;
        if(!c.contains(current)){
            c.add(current);
        }else{
            if(c.get(0)==current)
                return 0;
            else
                return -1;
        }
       // o.println(c);
        int idx = dfs(a,a[current],c);
        return idx;
    }

    public static long gcd(long n1, long n2) {
        long r;
        while (n2 != 0) {
            r = n1 % n2;
            n1 = n2;
            n2 = r;
        }
        return n1;
    }

    public static long pow(long x, long n, long mod) {
        long res = 1;
        x %= mod;
        while (n > 0) {
            if (n % 2 == 1) {
                res = (res * x) % mod;
            }
            x = (x * x) % mod;
            n /= 2;
        }
        return res;
    }

    static class FasterScanner {
        private byte[] buf = new byte[1024];
        private int curChar;
        private int snumChars;

        public int read() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = System.in.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public String nextString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n, int f) {
            if (f == 0) {
                int[] arr = new int[n];
                for (int i = 0; i < n; i++) {
                    arr[i] = nextInt();
                }
                return arr;
            } else {
                int[] arr = new int[n + 1];
                for (int i = 1; i < n + 1; i++) {
                    arr[i] = nextInt();
                }
                return arr;
            }
        }

        public long[] nextLongArray(int n, int f) {
            if (f == 0) {
                long[] arr = new long[n];
                for (int i = 0; i < n; i++) {
                    arr[i] = nextLong();
                }
                return arr;
            } else {
                long[] arr = new long[n + 1];
                for (int i = 1; i < n + 1; i++) {
                    arr[i] = nextLong();
                }
                return arr;
            }
        }

        private boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }
    }
}

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class ArpasLoudOwfAndMehrdadsEvilPlan implements Closeable {

    private InputReader in = new InputReader(System.in);
    private PrintWriter out = new PrintWriter(System.out);

    public void solve() {
        int n = in.ni();
        int[] x = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            x[i] = in.ni();
        }
        int result = 1;
        boolean[] visited = new boolean[n + 1];
        for (int i = 1; i <= n; i++) {
            int current = i;
            int t = 0;
            while (!visited[current]) {
                visited[current] = true;
                t++;
                current = x[current];
            }
            if (current != i) {
                out.println(-1);
                return;
            }
            if (t % 2 == 0) t /= 2;
            if (t >= 1) {
                result = lcm(result, t);
            }
        }
        out.println(result);
    }

    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    private int lcm(int a, int b) {
        return (a / gcd(a, b)) * b;
    }

    @Override
    public void close() throws IOException {
        in.close();
        out.close();
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int ni() {
            return Integer.parseInt(next());
        }

        public long nl() {
            return Long.parseLong(next());
        }

        public void close() throws IOException {
            reader.close();
        }
    }

    public static void main(String[] args) throws IOException {
        try (ArpasLoudOwfAndMehrdadsEvilPlan instance = new ArpasLoudOwfAndMehrdadsEvilPlan()) {
            instance.solve();
        }
    }
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;

import java.io.IOException;
import java.io.PrintWriter;

public class C_383 {
	public static int mod = 1000000007;
	static FastReader scan = new FastReader();
	static PrintWriter out = new PrintWriter(System.out);
	public static ArrayList<Integer> A;
	static boolean visited[];
	static int arr[];
	static ArrayList<Integer> T = new ArrayList<>();

	public static void main(String args[]) {
		/******************* code ***********************/
		int n = scan.nextInt();
		ArrayList<ArrayList<Integer>> Arr = new ArrayList<>();
		arr = new int[n + 1];
		int flag = 0;
		for (int i = 0; i <= n; i++) {
			Arr.add(new ArrayList<>());
		}
		for (int i = 1; i <= n; i++) {
			arr[i] = scan.nextInt();
			Arr.get(i).add(arr[i]);
		}
		int dgree[] = new int[n + 1];
		for (int i = 1; i <= n; i++) {
			for (int j : Arr.get(i)) {
				dgree[j]++;
			}

		}
		for (int i = 1; i <= n; i++) {
			if (dgree[i] == 0)
				flag = 1;
		}
		if (flag == 1) {
			out.println(-1);
		} else {
			A = new ArrayList<>();

			long sum = 1;
			visited = new boolean[n + 1];

			for (int i = 1; i <= n; i++) {
				if (!visited[i]) {
					dfs(i, i, 1);

					A = new ArrayList<>();
				}
			}
			long ans = 0;
			for (int i : T) {
				ans = i;
				break;
			}
			for (int i : T) {
				ans = gcd(ans, i);
				sum = sum * i / gcd(sum, i);
			}
			out.println(sum);
			//out.println(T);
		}
		// debug(arr);
		out.close();

	}

	static long gcd(long a, long b) {
		long r, i;
		while (b != 0) {
			r = a % b;
			a = b;
			b = r;
		}
		return a;
	}

	public static void dfs(int a, int root, int i) {
		A.add(a);
		visited[a] = true;
		if (!visited[arr[a]]) {

			dfs(arr[a], root, i + 1);
		} else {
			if (A.get(0) == arr[a]) {
				int size = A.size();
				A.clear();
				if (size % 2 == 0)
					size = size / 2;
				T.add(size);
			}
		}
	}

	static class Pair implements Comparable<Pair> {
		int x;
		int y;

		Pair(int xx, int yy) {
			x = xx;
			y = yy;
		}

		@Override
		public int compareTo(Pair o) {
			if (Long.compare(this.y, o.y) != 0)
				return Integer.compare(this.y, o.y);
			else
				return Long.compare(this.x, o.x);
		}
	}

	public static void debug(Object... o) {
		System.out.println(Arrays.deepToString(o));
	}

	public static long pow(long x, long n, long mod) {
		long res = 1;
		x %= mod;
		while (n > 0) {
			if (n % 2 == 1) {
				res = (res * x) % mod;
			}
			x = (x * x) % mod;
			n /= 2;
		}
		return res;
	}

	/************** Scanner ********************/
	static class FastReader {
		private byte[] buf = new byte[1024];
		private int curChar;
		private int snumChars;

		public int read() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = System.in.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public String nextLine() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public long nextLong() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		public long[] nextLongArray(int n) {
			long[] arr = new long[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLong();
			}
			return arr;
		}

		private boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

	}

}

import java.io.*;
import java.util.*;

public class p741a {
    static class Pair
    {
        public int a,b;
        public Pair(int a, int b)
        {
            this.a=a;
            this.b=b;
        }
    }
    public static long hcf(long a, long b)
    {
        if(a==0 || b==0)
            return a+b;
        return hcf(b,a%b);
    }
    public static long lcm(long a, long b)
    {
        return (a*b)/hcf(a,b);
    }
	public static void main(String[] args)throws IOException {
        InputReader in = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = in.nextInt();
        int arr[] = new int[n];
        for(int i=0;i<n;i++)
            arr[i]=in.nextInt()-1;
        long rep[] = new long[n];
        Arrays.fill(rep,-1);
        long lc = 1;
		for(int i=0;i<n;i++)
        {
            int v=i;
            for(int j=0;j<n;j++)
            {
                v=arr[v];
                if(v==i)
                {
                    long val = ((j+1)%2!=0) ? (j+1) : (j+1)/(int)2;
                    // if((j+1))
                    // long val = (long)Math.min(1,(j+1)/(int)2);
                    rep[i]=val; lc=lcm(rep[i],lc);
                    break;
                }
            }
        }
        // for(int i=0;i<n;i++)
            // out.print(rep[i]+" ");
        // out.println();
        for(int i=0;i<n;i++)
        {
            // long val=-1;
            // if(rep[i]!=-1)
                // val = lc/rep[i];
            if(rep[i]==-1)
            {
                out.println(-1); out.close(); return;
            }
        }
        out.println(lc);
        out.close();
	}
    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

    }

}

import java.io.*;
import java.util.*;

public class CF_C {
	public static void main(String[] args) {
		new CF_C().run();
	}
	public void run(){
		FastScanner sc = new FastScanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		int n = sc.nextInt();
		int[] a = new int[n+1];
		boolean[] b = new boolean[n+1];
		boolean isNo = false;
		ArrayList<Integer> steps = new ArrayList<Integer>();

		for(int i = 1;i<=n;i++){
			int tmp = sc.nextInt();
			a[i] = tmp;
			if(b[tmp]==true){
				isNo = true;
			}else{
				b[tmp] = true;
			}
		}
		if(isNo){
			out.println(-1);
			out.close();
			return ;
		}
		boolean[] vis = new boolean[n+1];
		long ans = 1;
		for(int i = 1;i<=n;i++){
			if(vis[i])
				continue;
			vis[i] = true;
			int len = 1;
			for(int j = a[i];!vis[j];j = a[j]){
				len++;
				vis[j]=true;
			}
			if((len&1)==0)
				len/=2;
			ans = sc.lcm(len, ans);
		}
		out.println(ans);
		out.close();
	}
}

class FastScanner {
	public BufferedReader br;
	public StringTokenizer st;

	public FastScanner(InputStream in) {
		br = new BufferedReader(new InputStreamReader(in));
		st = null;
	}

	public boolean hasMoreTokens() {
		while (st == null || !st.hasMoreTokens()) {
			String line = null;
			try {
				line = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (line == null)
				return false;
			st = new StringTokenizer(line);
		}
		return true;
	}

	public String next() {
		if (!hasMoreTokens())
			return null;
		return st.nextToken();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}

	public long nextLong() {
		return Long.parseLong(next());
	}

	public int[] readIntArray(int n) {
		int[] array = new int[n];
		for (int i = 0; i < n; i++) {
			array[i] = nextInt();
		}
		return array;
	}

	public long[] readLongArray(int n) {
		long[] array = new long[n];
		for (int i = 0; i < n; i++) {
			array[i] = nextLong();
		}
		return array;
	}

	public String[] readStringArray(int n) {
		String[] a = new String[n];
		for (int i = 0; i < n; i++) {
			a[i] = next();
		}
		return a;
	}

	public void shuffleIntArray(int[] a) {
		Random rand = new Random();
		for (int i = 0; i < a.length; i++) {
			int x = rand.nextInt(i + 1); // 0~i
			int t = a[i];
			a[i] = a[x];
			a[x] = t;
		}
	}

	// 只适合比较小的数，太大的数会越界
	public long factorial(long n) {
		if (n == 0)
			return 1L;
		long res = 1;
		for (long i = 2; i <= n; i++) {
			res *= i;
		}
		return res;
	}

	// 只适合比较小的数，太大的数会越界
	public long combination(long mom, long son) {
		return factorial(mom) / (factorial(son) * factorial(mom - son));
	}

	public long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	public long lcm(long a, long b) {
		return a * b / (gcd(a, b));
	}
}

import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;

public class ArpasLoudOwfandMehrDadsEvilPlan {
	static int[] a;
	static boolean[] b;
	static ArrayList<ArrayList<Integer>> cycles;
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		TreeSet<Integer> t = new TreeSet<>();
		a = new int[n];
		for(int i = 0 ; i < n ; i++){
			a[i] = scan.nextInt();
			t.add(a[i]);
		}
		if(t.size() < a.length){
			System.out.println(-1);
			return;
		}
		cycles = new ArrayList<>();
		b = new boolean[n];
		for(int i = 0 ; i < n ; i++){
			if(!b[i]){
				cycles.add(new ArrayList<>());
				cycles.get(cycles.size()-1).add(i);
				b[i] = true;
				dfs(a[i]-1, 1);
			}
		}
		long ans = cycles.get(0).size()%2 == 0?cycles.get(0).size()/2:cycles.get(0).size();
		for(int i = 1 ; i < cycles.size() ; i++){
			ans = lcm(ans, (cycles.get(i).size()%2 == 0?cycles.get(i).size()/2:cycles.get(i).size()));
		}
		System.out.println(ans);
	}
	static long gcd(long a, long b){
		if(a < b){
			long temp = b;
			b = a;
			a = temp;
		}
		while(b > 0){
			long temp = b;
			b = a%b;
			a = temp;
		}
		return a;
	}
	static long lcm(long a, long b){
		return a * (b / gcd(a, b));
	}
	static void dfs(int curr, int count){
		b[curr] = true;
		cycles.get(cycles.size()-1).add(a[curr]);
		if(!b[a[curr]-1]) dfs(a[curr]-1, count++);
	}
}

import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;

public class C {
    private FastScanner in = new FastScanner(System.in);
    private PrintWriter out;

    public C(PrintWriter out) {
        this.out = out;
    }

    public static class FastScanner {
        private BufferedReader br;
        private StringTokenizer st = null;

        public FastScanner(InputStream in) {
            br = new BufferedReader(new InputStreamReader(in));
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public boolean hasNext() throws IOException {
            while (st == null || !st.hasMoreTokens()) {
                String line = br.readLine();
                if (line == null)
                    return false;
                st = new StringTokenizer(line);
            }
            return true;
        }

        public String next() throws IOException {
            if (!hasNext()) {
                return null;
            }
            return st.nextToken();
        }
    }

    void solve() throws IOException {
        int n = in.nextInt();
        int[] crush = new int[n];
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
        }
        boolean[] vis = new boolean[n];
        long answ = 1;
        for (int i = 0; i < crush.length; i++) {
            if (vis[i]) {
                continue;
            }
            int cnt = 0;
            int j = i;
            while (!vis[j]) {
                vis[j] = true;
                j = crush[j];
                cnt++;
            }

            if (j != i) {
                out.println(-1);
                return;
            }

            answ = answ * cnt / gcd(answ, cnt);
        }
        if (answ % 2 == 0) {
            out.println(answ / 2);
        } else {
            out.println(answ);
        }
    }

    private long gcd(long a, long b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    public static void main(String[] args) {
        try {
            try (PrintWriter out = new PrintWriter(System.out)) {
                new C(out).solve();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

import java.util.*;

public class ArpasLoudOwfAndMehrdadsEvilPlan_741A {
	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = sc.nextInt() - 1;
		}
		TreeSet<Integer> s = new TreeSet<Integer>();
		for (int i = 0; i < n; i++) {
			s.add(i);
		}
		TreeSet<Integer> sizes = new TreeSet<Integer>();
		while (!s.isEmpty()) {
			int c = s.first();
			s.remove(c);
			int k = 1;
			int cur = a[c];
			while (s.contains(cur)) {
				s.remove(cur);
				cur = a[cur];
				k++;
			}
			if (cur != c) {
				System.out.println(-1);
				return;
			}
			sizes.add(k);
		}
		int l = 1;
		while (!sizes.isEmpty()) {
			int k = sizes.first();
			l = lcm(l, k);
			sizes.remove(k);
		}
		if (l % 2 == 0) {
			l = l / 2;
		}
		System.out.println(l);
	}
	public static int gcd(int a, int b) {
		if (b == 0) {
			return a;
		}
		else {
			return gcd(b, a % b);
		}
	}
	public static int lcm(int a, int b) {
		return (a * b) / gcd(a,b);
	}
}

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created by Frog on 2016/11/19.
 */
public class Main {
    static int[] arr;
    static boolean[] vis;
    static int n;

    public static void solve() {
        List<Integer> ans = new ArrayList<>();

        for (int i = 1; i <= n; ++i) {
            if (vis[i] == false) {
                int len = getLen(i);
                if (len == -1) {
                    System.out.println(-1);
                    return;
                }
                ans.add(len);
            }
        }

        BigInteger b = BigInteger.ONE;
        for (int num : ans) {
            if (num % 2 == 0) {
                b = lcm(b, num / 2);
            }
            else {
                b = lcm(b, num);
            }
        }
        System.out.println(b);
    }

    private static int getLen(int u) {
        vis[u] = true;
        int step = arr[u];
        int len = 1;
        while (step != u) {
            if (vis[step]) {
                return -1;
            }
            vis[step] = true;
            step = arr[step];
            ++len;
        }
        return len;
    }

    public static BigInteger lcm(BigInteger a, int bb) {
        BigInteger b = BigInteger.valueOf(bb);
        BigInteger gcd = b.gcd(a);
        return a.divide(gcd).multiply(b);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        vis = new boolean[n + 10];
        arr = new int[n + 10];
        for (int i = 1; i <= n; ++i) {
            arr[i] = in.nextInt();
        }
        solve();
        in.close();
    }
}

import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;

public class a {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int[] p = new int[n];
		boolean[] vs = new boolean[n];
		for(int i=0;i<n;i++) {
			p[i] = in.nextInt()-1;
			if(vs[p[i]]) {
				System.out.println(-1);
				return;
			}
			vs[p[i]]= true;
		}
		Arrays.fill(vs, false);
		ArrayDeque<Integer> q = new ArrayDeque<>();
		long ans = 1;
		for(int i=0;i<n;i++) {
			if(vs[i]) continue;
			int len = 0;
			int c = i;
			while(!vs[c]) {
				vs[c] = true;
				len++;
				c = p[c];
			}
			if(len % 2 == 0)
				len /= 2;
			ans = ans/gcd(ans,len)*len;
		}
		System.out.println(ans);
	}
	static long gcd(long a, long b) {
		return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue();
	}
}

// Main Code at the Bottom
import java.util.*;
import java.io.*;
public class Main{
	//Fast IO class
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
        	boolean env=System.getProperty("ONLINE_JUDGE") != null;
        	if(!env) {
        		try {
					br=new BufferedReader(new FileReader("src\\input.txt"));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
        	}
        	else br = new BufferedReader(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    static long MOD=1000000000+7;
    //debug
    static void debug(Object... o) {
        System.out.println(Arrays.deepToString(o));
    }
    // Pair
    static class pair{
    	long x,y;
    	pair(long a,long b){
    		this.x=a;
    		this.y=b;
    	}
    	public boolean equals(Object obj) {
    		if(obj == null || obj.getClass()!= this.getClass()) return false;
            pair p = (pair) obj;
            return (this.x==p.x && this.y==p.y);
        }
    	public int hashCode() {
            return Objects.hash(x,y);
        }
    }
    static FastReader sc=new FastReader();
    static PrintWriter out=new PrintWriter(System.out);
    //Global variables and functions
    static int gcd(int a,int b) {
    	return b==0?a:gcd(b,a%b);
    }
    static int lcm(int a,int b) {
    	return (a*b)/(gcd(a,b));
    }
    //Main function(The main code starts from here)
    public static void main (String[] args) throws java.lang.Exception {
    	int test=1;
    	//test=sc.nextInt();
    	while(test-->0) {
    		int n=sc.nextInt();
    		int a[]=new int[n];
    		for(int i=0;i<n;i++) a[i]=sc.nextInt()-1;
    		int visited[]=new int[n];
    		int ans=1;
    		for(int i=0;i<n;i++) {
    			if(visited[i]==1) continue;
    			int cnt=0,cur=i;
    			while(visited[cur]==0) {
    				visited[cur]=1;
    				cnt++;
    				cur=a[cur];
    			}
    			if(cur!=i) {
    				ans=-1;
    				break;
    			}
    			if(cnt%2==0) ans=lcm(ans,cnt/2);
    			else ans=lcm(ans,cnt);
    		}
    		out.println(ans);
    	}
        out.flush();
        out.close();
    }
}

import java.io.*;
import java.util.*;

public class Template implements Runnable {

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void init() throws FileNotFoundException {
        try {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        } catch (Exception e) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            try {
                tok = new StringTokenizer(in.readLine(), " :");
            } catch (Exception e) {
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    int[] readIntArray(int size) throws IOException {
        int[] res = new int[size];
        for (int i = 0; i < size; i++) {
            res[i] = readInt();
        }
        return res;
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    <T> List<T>[] createGraphList(int size) {
        List<T>[] list = new List[size];
        for (int i = 0; i < size; i++) {
            list[i] = new ArrayList<>();
        }
        return list;
    }

    public static void main(String[] args) {
        new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
    }

    long timeBegin, timeEnd;

    void time() {
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    long memoryTotal, memoryFree;

    void memory() {
        memoryFree = Runtime.getRuntime().freeMemory();
        System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
                + " KB");
    }

    public void run() {
        try {
            timeBegin = System.currentTimeMillis();
            memoryTotal = Runtime.getRuntime().freeMemory();
            init();
            solve();
            out.close();
            if (System.getProperty("ONLINE_JUDGE") == null) {
                time();
                memory();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    long gcd(long a, long b) {
        return a == 0 ? b : gcd(b % a, a);
    }

    long lcm(long a, long b) {
        return a * b / gcd(a, b);
    }

    void solve() throws IOException {
        int n = readInt();
        int[] a = readIntArray(n);
        boolean[] hasIncoming = new boolean[n];
        for (int i = 0; i < n; i++) {
            int to = a[i] - 1;
            if (hasIncoming[to]) {
                out.println(-1);
                return;
            }
            hasIncoming[to] = true;
        }

        boolean[] used = new boolean[n];
        long answer = 1;
        for (int i = 0; i < n; i++) {
            if (used[i]) continue;
            int cur = i;
            int len = 1;
            while (a[cur] - 1 != i) {
                cur = a[cur] - 1;
                len++;
            }
            if (len % 2 == 0) {
                len /= 2;
            }
            answer = lcm(answer, len);
        }
        out.println(answer);

    }

}

    import java.util.*;
        import java.math.*;
        import java.io.*;
        import java.text.DecimalFormat;
        import java.math.BigInteger;
        public class Main{
            //static int d=20;
            static long mod=1000000007 ;
            static HashMap<String,Double> hm=new HashMap<>();
            static ArrayList<ArrayList<Integer>> arr;
            static long[][] color;
            static int[] a;
            static int[] vis,num;
            static double val;
            public static void main(String[] args)  throws IOException {
                boolean online =false;
                String fileName = "C-large-practice";
                PrintWriter out;
                if (online) {
                    s.init(new FileInputStream(new File(fileName + ".in")));
                     out= new PrintWriter(new FileWriter(fileName + "out.txt"));
                }
                 else {
                    s.init(System.in);

                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
                }
                int n=s.ni();
                int[] a=new int[n];
                for(int i=0;i<n;i++)
                    a[i]=s.ni()-1;
                int[] cycle=new int[n];
                Arrays.fill(cycle,-1);
                int flag=0;
                int[] c=new int[n];
                Arrays.fill(c,-1);
                int ct=0;
               // int ans=-1;
                ArrayList<Integer> arr=new ArrayList<>();
                for(int i=0;i<n;i++){
                    if(c[i]!=-1)
                        continue;
                    int pre=i;
                    int sz=0;

                    while(c[i]==-1){
                        c[i]=ct;
                        i=a[i];
                        sz++;
                    }
                    ct++;

                    if(pre!=i || (sz==1 && pre!=a[pre] )){
                        flag=1;
                        break;
                    }
                    if(sz%2==0)
                        sz/=2;
                    arr.add(sz);
                }
                if(flag==1 || arr.size()==0)
                    out.println(-1);

                else if(arr.size()==1)
                    out.println(arr.get(0));
                else{
                    long z=gcd(arr.get(0)*1L,arr.get(1)*1L);
                    long ans=(arr.get(0)*1L * arr.get(1)*1L)/z;
                    for(int i=2;i<arr.size();i++){
                        z=gcd(arr.get(i)*1L,ans);
                        ans=(arr.get(i)*1L * ans)/z;

                    }
                    out.println(ans);
                }
                out.close();

            }
            public static long gcd(long a,long b){
                if(a%b==0)
                    return b;
                else
                    return gcd(b,a%b);
            }
            public static long pow2(long a,long b){
                    long ans=1;
                    while(b>0){
                        if(b%2==1)
                            ans=(a*ans);
                        a=(a*a);
                        b/=2;
                    }
                    return  ans;
            }
            public static double pow3(double a,long b){
                    double ans=1;
                    while(b>0){
                        if(b%2==1)
                            ans=(a*ans);
                        a=(a*a);
                        b/=2;
                    }
                    return  ans;
            }

             static class name implements Comparable<name> {
                int id,p,g;
                public name(int  x,int y,int z){
                    id=x;
                    p=y;
                    g=z;
                }
                public int compareTo(name o){

                        return id-o.id;
                }
            }
            public static class s {
                static BufferedReader reader;
                static StringTokenizer tokenizer;

                /** call this method to initialize reader for InputStream */
                static void init(InputStream input) {
                    reader = new BufferedReader(
                                new InputStreamReader(input) );
                    tokenizer = new StringTokenizer("");
                }

                /** get next word */
                static String ns() throws IOException {
                    while ( ! tokenizer.hasMoreTokens() ) {
                        //TODO add check for eof if necessary
                        tokenizer = new StringTokenizer(
                            reader.readLine() );
                    }
                    return tokenizer.nextToken();
                }

                static int ni() throws IOException {
                    return Integer.parseInt( ns() );
                }

                static double nd() throws IOException {
                    return Double.parseDouble( ns() );
                }
                static long nl() throws IOException {
                    return Long.parseLong( ns() );
                }

            }
        }

import java.io.*;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;

public class C {

    final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void solve() throws IOException {
        int n = readInt();
        int[] crush = new int[n];
        int[] count = new int[n];
        for(int i = 0; i < n; i++) {
            crush[i] = readInt() - 1;
            count[crush[i]]++;
        }

        if(Arrays.stream(count).anyMatch(x -> x != 1)) {
            out.println(-1);
            return;
        }
        long res = 1;
        boolean[] used = new boolean[n];
        for(int i = 0; i < n; i++) {
            if(used[i]) continue;

            int cur = i;
            int step = 0;
            while (true) {
                used[cur] = true;
                step++;
                cur = crush[cur];
                if(cur == i) break;
            }
            if (step % 2 == 0) step /= 2;
            long gcd = gcd(res, step);
            res *= step / gcd;
        }
        out.println(res);
    }
    long gcd(long a, long b) {
        if(a == 0) return b;
        if(b == 0) return a;
        if(a > b) return gcd(a%b, b);
        else return gcd(a, b % a);
    }

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    int[] readArr(int n) throws IOException {
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = readInt();
        }
        return res;
    }

    long[] readArrL(int n) throws IOException {
        long[] res = new long[n];
        for (int i = 0; i < n; i++) {
            res[i] = readLong();
        }
        return res;
    }

    public static void main(String[] args) {
        new C().run();
    }

    public void run() {
        try {
            long t1 = System.currentTimeMillis();
            init();
            solve();
            out.close();
            long t2 = System.currentTimeMillis();
            System.err.println("Time = " + (t2 - t1));
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }
}

import java.util.Scanner;

public class Crush2 {

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int a[] = new int[n];
		for(int i=0;i<n;i++)
		{
			a[i] = sc.nextInt();
		}
		boolean flag=false;
		int c[] = new int[n];
		for(int i=0;i<n;i++)
		{
			int f[] = new int[n];
			int j=i;
			while(true)
			{
				if(j==a[j]-1)
				{
					if(j==i)
					{
						c[i]++;
					}
					else
					{
						flag=true;
						i=n-1;
						System.out.println("-1");
					}

					break;
				}
				if(a[j]-1==i)
				{
					if(c[i] > 1)
						c[i]++;
					break;
				}
				if(f[j]==1)
				{
					flag=true;
					System.out.println("-1");
					i=n-1;
					break;
				}
				else
				{

					f[j] = 1;
					j=a[j]-1;
					c[i]++;
				}

			}//end while
			//System.out.println("c : "+c[i]);
			if(c[i]%2==0)
				c[i] = c[i]/2;
		}//for loop
		if(flag==false)
			System.out.println(lcm(c));
	}//main

	private static int gcd(int a, int b)
	{
	    while (b > 0)
	    {
	        int temp = b;
	        b = a % b;
	        a = temp;
	    }
	    return a;
	}

	private static int gcd(int[] input)
	{
		int result = input[0];
	    for(int i = 1; i < input.length; i++) result = gcd(result, input[i]);
	    return result;
	}

	private static int lcm(int a, int b)
	{
	    return a * (b / gcd(a, b));
	}

	private static int lcm(int[] input)
	{
		int result = input[0];
	    for(int i = 1; i < input.length; i++) result = lcm(result, input[i]);
	    return result;
	}

}

import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {

        File file = new File("in.txt");
        InputStream inputStream = null;
        // try {inputStream= new FileInputStream(file);} catch (FileNotFoundException ex){return;};
        inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskB {

    private Map<Integer, Integer> outgoingEdges;
    private Map<Integer, Integer> incomingEdges;
    private Set<Integer> visited;
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        Integer lCommonMultiple=1;
        Integer numberOfNodes = in.nextInt();
        incomingEdges = new HashMap<>();
        outgoingEdges = new HashMap<>();
        visited = new HashSet<>();
        for(int i=0; i<numberOfNodes; i++){
            int j = in.nextInt()-1;
            outgoingEdges.put(i,j);
            if(incomingEdges.containsKey(j)){
                out.println("-1");
                return;
            }
            incomingEdges.put(j,i);
        }
        for(int i=0; i<numberOfNodes; i++ ){
            if(!incomingEdges.containsKey(i)){
                out.println("-1");
                return;
            }
        }
        for(int i=0; i<numberOfNodes; i++){
            if(visited.contains(i)){
                continue;
            }
            Integer cycleLength = 1;
            visited.add(i);
            Integer nextNode = outgoingEdges.get(i);
            while(nextNode!=i){
                cycleLength+=1;
                visited.add(nextNode);
                nextNode = outgoingEdges.get(nextNode);
            }

            if(cycleLength % 2 == 0){
                cycleLength /=2;
            }
            lCommonMultiple = lcm(lCommonMultiple, cycleLength);

        }
        out.println(lCommonMultiple);
    }

    public int gcd(Integer a, Integer b){
        if(b == 0){
            return a;
        }
        return gcd(b, a % b);
    }

    public int lcm(Integer a, Integer b){
        return (a / gcd(a,b)) * b;
    }

}

class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;

    public InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream), 32768);
        tokenizer = null;
    }

    public String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    public String nextLine(){
        try {
            return reader.readLine();
        } catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }
    public long nextLong() { return Long.parseLong(next()); }

}

class Pair<F, S> {
    public final F first;
    public final S second;

    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }
        Pair<?, ?> p = (Pair<?, ?>) o;
        return Objects.equals(p.first, first) && Objects.equals(p.second, second);
    }

    @Override
    public int hashCode() {
        return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
    }

    @Override
    public String toString() {
        return "(" + first + ", " + second + ')';
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.AbstractCollection;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.LinkedList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Vikash Kumar
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        Codeforces solver = new Codeforces();
        solver.solve(1, in, out);
        out.close();
    }

    static class Codeforces {
        public void solve(int testNumber, InputReader in, OutputWriter out) throws IndexOutOfBoundsException {
            int n = in.ni();
            HashSet<Integer>[] arr = new HashSet[n + 1];
            for (int i = 1; i <= n; i++) {
                arr[i] = new HashSet<>();
            }
            HashSet<Integer> set;
            for (int i = 1; i <= n; i++) {
                int now = in.ni();
                arr[i].add(now);
                arr[now].add(now);
            }
            for (int i = 1; i <= n; i++) {
                if (arr[i].size() == 1 && arr[i].contains(i)) {
                    continue;
                } else if (arr[i].size() != 2) {
                    out.println(-1);
                    return;
                }
            }
            boolean[] vis = new boolean[n + 1];
            int ans = 1;
            for (int i = 1; i <= n; i++) {
                if (!vis[i]) {
                    vis[i] = true;
                    int count = 1;
                    LinkedList<Integer> queue = new LinkedList<>();
                    queue.add(i);
                    while (!queue.isEmpty()) {
                        int now = queue.poll();
                        Iterator<Integer> itr = arr[now].iterator();
                        while (itr.hasNext()) {
                            int next = itr.next();
                            if (!vis[next]) {
                                queue.add(next);
                                vis[next] = true;
                                count++;
                            }
                        }
                    }
                    if (count % 2 == 0) {
                        count /= 2;
                    }
                    ans = lcm(ans, count);
                }
            }
            out.println(ans);
        }

        int lcm(int x, int y) {
            return (x * y) / gcd(x, y);
        }

        int gcd(int a, int b) {
            if (a == 0) {
                return b;
            }
            return gcd(b % a, a);
        }

    }

    static class InputReader {
        private BufferedReader br;
        private StringTokenizer st;

        public InputReader(InputStream inputStream) {
            br = new BufferedReader(new InputStreamReader(inputStream));
        }

        public String n() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                }
            }
            return st.nextToken();
        }

        public int ni() {
            return Integer.parseInt(n());
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }
}

import java.util.*;

public class M{
    static Scanner sc;
    public static void swap(long a, long b){
		long tmp = a;
		a = b;
		b = tmp;
	}
    public static long gcd(long a,long b)
    {
	    if(b>a)
		    swap(a,b);
        long c;
	    while(b>0)
	    {
		    c=a%b;	a=b;	b=c;
	    }
	    return a;
    }

    public static void main(String []args){
        sc = new Scanner(System.in);
        int n=sc.nextInt();
        int num=1;
        int []a=new int[n+1];
        int []b=new int[n+1];
        while (sc.hasNext()){
            a[num]=sc.nextInt();
            num++;
        }
        long ans=1;
		int flag=0;
		for(int i=1;i<=n;++i)
		{
			if(b[i]==1)
				continue;
			long temp=1;
			int y=a[i];
			b[i]=1;
			while(y!=i){
				b[y]=1;
				y=a[y];
				temp++;
				if(temp>n){
					flag=1;
					break;
				}
			}
			if(flag==1)
				break;
			if(temp%2==0)
				temp/=2;
			ans = ans/gcd(ans,temp)*temp;
		}
		if(flag==1)
			System.out.print("-1\n");
		else System.out.print(ans);
    }
}

import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;

public class CF741A {
	/**
	 * solution result
	 */
	public static class Answer {
		long n;
		public Answer(long n) {
			this.n = n;
		}

		@Override
		public String toString() {
			return Long.toString(n);
		}
	};

	/**
	 * input parser
	 */
	public static class Input {
		int n;
		int a[];
		public Input(Scanner sc) {
			n = sc.nextInt();
			a = new int[n];
			for (int i=0; i<n; i++)
				a[i] = sc.nextInt()-1;
		}
	};

	static long gcd(long a, long b)	{
	    while (b > 0) {
	        long temp = b;
	        b = a % b;
	        a = temp;
	    }
	    return a;
	}

	static long lcm(long a, long b)	{
	    return a * (b / gcd(a, b));
	}

	/**
	 * solver function
	 */
	public static Answer solve(Input in) {
		boolean v[] = new boolean[in.a.length];
		int loop[] = new int[in.a.length];
		int nl = 0;
		for (int i=0; i<in.a.length; i++) {
			int j = i;
			int cnt = 0;
			while (!v[j]) {
				cnt++;
				v[j] = true;
				j = in.a[j];
			}
			if (cnt > 0) {
				if (j != i)
					return new Answer(-1);
				if (cnt%2 == 0)
					loop[nl++] = cnt/2;
				else
					loop[nl++] = cnt;
			}
		}
		if (nl > 0) {
			// uniq+lcm
			Arrays.sort(loop, 0, nl-1);
			int prev = loop[0];
			long lcm = prev;
			for (int i=1; i<nl; i++) {
				if (loop[i] != prev) {
					prev = loop[i];
					lcm = lcm(lcm, prev);
				}
			}
			return new Answer(lcm);
		} else {
			return new Answer(1);
		}
	}

	/**
	 * standard executable mantra
	 */
	public static void proc(Scanner sc, PrintStream out) {
		Input in = new Input(sc);
		out.println(solve(in));
	}

	public static void main(String[] args) {
		try (Scanner sc = new Scanner(System.in)) {
			proc(sc, System.out);
		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigInteger;
import java.util.*;

public class C {
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();

        int n = sc.nextInt();
        int[] arr = new int[n];
        arr = sc.readIntArray(n);
        for(int a = 0; a < n; a++){
        	arr[a]--;
        }
        ArrayList<Integer> cycleLengths = new ArrayList<Integer>();
        for(int a = 0; a < n; a++){
        	int i = getCycleLength(a, arr);
        	if(i > 500){
        		System.out.println(-1);
        		System.exit(0);
        	}
        	cycleLengths.add(i);
        }
        BigInteger lcm = bigLCM(cycleLengths);
        if(lcm.mod(BigInteger.valueOf(2)).equals(BigInteger.valueOf(1))){
        	System.out.println(lcm);
        }
        else{
        	System.out.println(lcm.divide(BigInteger.valueOf(2)));
        }
    }

    private static BigInteger bigLCM(ArrayList<Integer> cycleLengths) {
		// TODO Auto-generated method stub
    	BigInteger start = BigInteger.ONE;
    	for(Integer i:cycleLengths){
    		BigInteger gcd = start.gcd(BigInteger.valueOf(i));
    		start = start.multiply(BigInteger.valueOf(i)).divide(gcd);
    	}
		return start;
	}

	private static int getCycleLength(int a, int[] arr) {
		int start = a;
		int count = 1;
		int next = arr[start];
		while(start != next && count < 501){
			next = arr[next];
			count++;
		}
		// TODO Auto-generated method stub
		return count;
	}

	public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;
        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }
        public FastScanner() {
            this(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }
        long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextLong();
            }
            return a;
        }
    }
}

import java.io.*;
import java.util.*;

public class C
{

	FastScanner in;
	PrintWriter out;
	int i = 0, j = 0;

	void solve() {
		/**************START**************/
		int n = in.nextInt();
		int[] mapping = new int[n+1];
		BitSet bs = new BitSet(n+1);
		bs.set(1,n+1);
		for (i = 1; i <= n; i++)
		{

			mapping[i] = in.nextInt();
		}
		int[] cycle = new int[n+1];
		int[] cycleSize = new int[n+1];
		int curCycle = 1;
		TreeSet<Integer> sizes = new TreeSet<Integer>();
		while (!bs.isEmpty())
		{
			int startNode = bs.nextSetBit(0);
			bs.clear(startNode);
			cycle[startNode] = curCycle;
			cycleSize[curCycle] = 1;
			int nextNode = mapping[startNode];
			while (nextNode != startNode)
			{
				if (bs.get(nextNode))
				{
					cycle[nextNode] = curCycle;
					cycleSize[curCycle]++;
					bs.clear(nextNode);
					nextNode = mapping[nextNode];
				}
				else
				{
					out.println("-1");
					return;
				}
			}
			if (cycleSize[curCycle] > 2)
			{
				if (cycleSize[curCycle] % 2 == 0)
					sizes.add(cycleSize[curCycle]/2);
				else
					sizes.add(cycleSize[curCycle]);
			}
			curCycle++;
		}
		if (sizes.isEmpty())
		{
			out.println("1");
		}
		else if (sizes.size() == 1)
		{
			out.println((sizes.first()));
		}
		else
		{
			long result = (long)sizes.pollLast();
			while (!sizes.isEmpty())
			{
				result = lcm(result, (long)sizes.pollLast());
			}
			out.println(result);

		}

		/***************END***************/
	}
	long lcm(long a, long b)
	{
	    return a * (b / gcd(a, b));
	}
	long gcd(long a, long b)
	{
	    while (b > 0)
	    {
	        long temp = b;
	        b = a % b; // % is remainder
	        a = temp;
	    }
	    return a;
	}

	public static void main(String[] args) {
		new C().runIO();
	}

	void runIO() {
		in = new FastScanner(System.in);
		out = new PrintWriter(System.out);

		solve();

		out.close();
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(File f) {
			try {
				br = new BufferedReader(new FileReader(f));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		public FastScanner(InputStream f) {
			br = new BufferedReader(new InputStreamReader(f));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				String s = null;
				try {
					s = br.readLine();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (s == null)
					return null;
				st = new StringTokenizer(s);
			}
			return st.nextToken();
		}

		boolean hasMoreTokens() {
			while (st == null || !st.hasMoreTokens()) {
				String s = null;
				try {
					s = br.readLine();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (s == null)
					return false;
				st = new StringTokenizer(s);
			}
			return true;
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}
	}
}

/*package com.fancita.codeforces;*/

import java.io.*;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Random;

/**
 * Created by ashutosh on 6/12/16.
 */
public class c383 extends FastIO {
    public static void main(String[] args) {

        /*Random random = new Random();
        while (true) {
            int n = random.nextInt(10) + 1;
            writer.printLine("n = " + n);

            int[] arr = new int[n+1];
            for (int i = 1; i <= n; i++) {
                arr[i] = random.nextInt(n) + 1;
            }

            int a = run(arr, n);
            int b = runBrute(arr, n);
            writer.printLine(a);
            writer.printLine(b);
            if (a != b) {
                writer.printLine("a != b");
                writer.printLine(Arrays.toString(arr));
                break;
            }
        }

        writer.flush();
        writer.close();*/

        int n = reader.readInt();
        int[] arr = new int[n+1];
        IOUtils.readIntArray(reader, arr, 1);
        writer.printLine(run(arr, n));
        writer.flush();
        writer.close();
    }

    public static int run(int[] arr, int maxIndex) {
        int ret = 1;
        boolean[] visited = new boolean[maxIndex+1];
        for (int i = 1; i <= maxIndex; i++) {
            if (!visited[i]) {
                visited[i] = true;
                int start = i;
                int present = arr[i];
                int count = 1;
                while (start != present) {
                    if (visited[present]) {
                        count = Integer.MIN_VALUE;
                        break;
                    }
                    count++;
                    visited[present] = true;
                    present = arr[present];
                }
                if (count == Integer.MIN_VALUE) {
                    ret = Integer.MIN_VALUE;
                    break;
                } else count = count % 2 == 0 ? count / 2 : count;
                ret = lcm(ret, count);
            }
        }
        /*writer.print(ret < 0 ? -1 : ret);*/
        return ret < 0 ? -1 : ret;
    }

    public static int lcm(int a, int b) { return a * (b / gcd(a, b)); }

    public static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    public static int runBrute(int[] arr, int maxIndex) {
        int maxT = maxIndex;
        int t;
        for (t = 1; t <= maxT; t++) {
            if (t == maxT) {
                break;
            }
            boolean done = true;
            for (int i = 1; i <= maxIndex; i++) {
                int tIter =  1;
                int next = arr[i];
                while (tIter != t) {
                    tIter++;
                    next = arr[next];
                }

                int start = next;
                tIter = 1;
                next = arr[start];
                while (tIter != t) {
                    tIter++;
                    next = arr[next];
                }

                if (next != arr[i]) {
                    done = false;
                    break;
                }
            }

            if (done) {
                break;
            }

        }
        if (t == maxT) {
            /*writer.print(-1);*/
            return -1;
        } else {
            /*writer.print(t);*/
            return t;
        }

    }
}

class FastIO {

    public static InputReader reader = new InputReader(System.in);
    public static OutputWriter writer	=	new OutputWriter(System.out);

    public static class InputReader {

        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }

    public static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0)
                    writer.print(' ');
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

        public void flush() {
            writer.flush();
        }

    }

    public static class IOUtils {

        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++)
                array[i] = in.readInt();
            return array;
        }

        /**
         * Read items into array starting from a given point
         * @param in
         * @param arr
         * @param i is starting point
         */
        public static void readIntArray(InputReader in, int[] arr, int i) {
            int n = arr.length;
            for (int j = i; j < n; j++) {
                arr[j] = in.readInt();
            }
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class A_1_383 {
	static boolean visited[];
	public static void main(String args[]){
		Scan scan = new Scan(System.in);
		int n = scan.nextInt();
		int arr[] = new int[n+1];
		int degree[] = new int[n+1];
		for(int i=1;i<=n;i++){
			arr[i] = scan.nextInt();
			degree[arr[i]]++;
		}
		for(int i=1;i<=n;i++){
			if(degree[i]==0){
				System.out.println(-1);
				return;
			}
		}
		visited = new boolean[n+1];
		ArrayList<Integer> list = new ArrayList<Integer>();
		for(int i=1;i<=n;i++){
			if(visited[i]==false){
				int len = bfs(i,arr);
				if(len%2==0)
					len /= 2;
				list.add(len);
			}
		}
		int MOD = (int) 1e9 + 7;
		BigInteger res = BigInteger.valueOf(list.get(0));
        for (int x : list) {
            BigInteger X = BigInteger.valueOf(x);
            BigInteger g = res.gcd(X);
            res = res.multiply(X).divide(g);
        }
        System.out.println(res.mod(BigInteger.valueOf(MOD)));
	}
	public static int bfs(int i,int graph[]){
		ArrayList<Integer> len = new ArrayList<Integer>();
		ArrayList<Integer> que = new ArrayList<Integer>();
		que.add(i);
		while(!que.isEmpty()){
			int temp = que.remove(0);
			visited[temp] = true;
			len.add(temp);
			int next = graph[temp];

			if(visited[next]==true){
				return len.size();
			}
			que.add(next);
		}
		return len.size();
	}
	public static int gcd(int a,int b){
		if(a<b){
			int temp = a;
			a = b;
			b = temp;
		}
		while(b!=0){
			int temp = a%b;
			a = b;
			b = temp;
		}
		return a;
	}
	static class Scan{
		BufferedReader br;
		StringTokenizer token;
		Scan(InputStream input){
			br = new BufferedReader(new InputStreamReader(input));
			token = null;
		}
		public String next(){
			while(token==null || !token.hasMoreTokens() ){
				try {
					token = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return token.nextToken();
		}
		public char readChar() throws IOException{
			return (char)br.read();
		}
		public int nextInt(){
			return Integer.parseInt(next());
		}
		public long nextLong(){
			return Long.parseLong(next());
		}
	}
}

import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by YSingh on 24/12/16.
 */
public class ProblemC {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());
        String line2 = sc.nextLine();
        String[] numbers = line2.split(" ");
        int[] arr = new int[n + 1];

        for (int i = 0; i < numbers.length; i++) {
            arr[i + 1] = Integer.parseInt(numbers[i]);
        }

        int condition = getIndegree(arr, n + 1);
        long out = -1;
        if(condition == 1) {
            int len = 0;
            long [] lengths = new long[n];
            boolean [] visited = new boolean[n + 1];
            for (int i = 1; i <= n; i++) {
                Arrays.fill(visited, false);
                len = getCycleLen(i, arr, visited);

                if(len % 2 == 0) {
                    lengths[i - 1] = len / 2;
                }
                else {
                    lengths[i - 1] = len;
                }
            }

            out = getLCM(lengths);
        }

        System.out.println(out);
    }

    private static int getCycleLen(int i, int[] arr, boolean [] visited) {
        if(visited[i]) {
            return 0;
        }
        visited[i] = true;
        return 1 + getCycleLen(arr[i], arr, visited);
    }

    private static long getLCM(long[] numbers) {
        long res = 1;
        for (int i = 0; i < numbers.length; i++) {
            res = (res * numbers[i]) / gcd(res, numbers[i]);
        }

        return res;
    }

    private static long gcd(long a, long b) {
        if(a % b == 0) {
            return b;
        }

        return gcd(b, a % b);
    }

    private static int getIndegree(int[] arr, int n) {
        boolean [] visited = new boolean[n];
        Arrays.fill(visited, false);

        for (int i = 1; i < n; i++) {
            visited[arr[i]] = true;
        }

        int out = 1;

        for (int i = 1; i < n; i++) {
            if(!visited[i]) {
                out = 0;
                break;
            }
        }
        return out;
    }

}

import java.util.Scanner;

public class Crush {

	static final int Maxn = 100 + 5;
	static int[] crush = new int[Maxn];
	static boolean[] isCrush = new boolean[Maxn];
	static boolean[] mark = new boolean[Maxn];
	static long ans = 1;

	static int dfs(int v)
	{
		mark[v] = true;
		if(! mark[crush[v]])
			return 1 + dfs(crush[v]);
		return 1;
	}

	static long gcd(long a, long b) {
		if(b == 0)
			return a;
		return gcd(b, a % b);
	}

	public static void main(String[] args) {
		Scanner S = new Scanner(System.in);
		int n = S.nextInt();
		for(int i = 0; i < n; i ++) {
			crush[i] = S.nextInt();
			crush[i] --;
			isCrush[crush[i]] = true;
		}
		for(int i = 0; i < n; i ++)
			if(! isCrush[i]) {
				System.out.println(-1);
				return;
			}
		for(int i = 0; i < n; i ++) {
			if(!mark[i]) {
				long sz = dfs(i);
				if(sz % 2 == 0)
					sz /= 2;
				long a = ans;
				ans *= sz;
				if(sz > a)
				{
					long c = sz;
					sz = a;
					a = c;
				}
				ans /= gcd(a, sz);
			}
		}
		System.out.println(ans);
	}
}

import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;

public class ArpasLoudOwfandMehrDadsEvilPlan {
	static int[] a;
	static boolean[] b;
	static ArrayList<ArrayList<Integer>> cycles;
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		TreeSet<Integer> t = new TreeSet<>();
		a = new int[n];
		for(int i = 0 ; i < n ; i++){
			a[i] = scan.nextInt();
			t.add(a[i]);
		}
		if(t.size() < a.length){
			System.out.println(-1);
			return;
		}
		cycles = new ArrayList<>();
		b = new boolean[n];
		for(int i = 0 ; i < n ; i++){
			if(!b[i]){
				cycles.add(new ArrayList<>());
				cycles.get(cycles.size()-1).add(i);
				b[i] = true;
				dfs(a[i]-1, 1);
			}
		}
		long ans = cycles.get(0).size()%2 == 0?cycles.get(0).size()/2:cycles.get(0).size();
		for(int i = 1 ; i < cycles.size() ; i++){
			ans = lcm(ans, (cycles.get(i).size()%2 == 0?cycles.get(i).size()/2:cycles.get(i).size()));
		}
		System.out.println(ans);
	}
	static long gcd(long a, long b){
		if(a < b){
			long temp = b;
			b = a;
			a = temp;
		}
		while(b > 0){
			long temp = b;
			b = a%b;
			a = temp;
		}
		return a;
	}
	static long lcm(long a, long b){
		return a * (b / gcd(a, b));
	}
	static void dfs(int curr, int count){
		b[curr] = true;
		cycles.get(cycles.size()-1).add(a[curr]);
		if(!b[a[curr]-1]) dfs(a[curr]-1, count++);
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.readInt();
            int[] crush = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                crush[i] = in.readInt();
            }
            boolean visited[] = new boolean[n + 1];
            int ans = 1;
            for (int i = 1; i <= n; i++) {
                if (visited[i]) continue;
                visited[i] = true;
                int ed = 1;
                int j, k;
                for (j = crush[i], k = 0; j != i && k < n; j = crush[j], k++) {
                    visited[j] = true;
                    ed++;
                }
                if (j == i) {
                    ans = lcm(ans, ed % 2 == 0 ? ed / 2 : ed);
                } else {
                    out.println(-1);
                    return;
                }
            }
            out.println(ans);
        }

        int lcm(int a, int b) {
            return (a * b) / gcd(a, b);
        }

        int gcd(int a, int b) {
            while (b != 0) {
                int r = a % b;
                a = b;
                b = r;
            }
            return a;
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
//import Queue.node;
public class TestClass {
	private static InputStream stream;
	private static byte[] buf = new byte[1024];
	private static int curChar;
	private static int numChars;
	private static SpaceCharFilter filter;
	private static PrintWriter pw;
	static int di = 0,gi = 0;
	public static class Queue{
		private class node{
			int val;
			node next;
			node(int a){
				val = a;
				next = null;
			}
		}
		node head,tail;
		Queue(){
			head = null;
			tail = null;
		}
		public void EnQueue(int a){
			if(head==null){
				node p = new node(a);
				head = p;
				tail = p;
			}
			else{
				node p = new node(a);
				tail.next = p;
				tail = p;
			}
		}
		public int DeQueue(){
			int a = head.val;
			head = head.next;
			return a;
		}
		public boolean isEmpty(){
			return head==null;
		}
	}
    public static int pow(int x,int y,long m){
    	if(y==0)
    		return 1;
    	int k = pow(x,y/2,m);
    	if(y%2==0)
    		return (int)((k*(long)k)%m);
    	else
    		return (int)((((k*(long)k)%m)*x)%m);
    }
    static int Inversex = 0,Inversey = 0;
    public static void InverseModulo(int a,int m){
    	if(m==0){
    		Inversex = 1;
    		Inversey = 0;
    	}
    	else{
    		InverseModulo(m,a%m);
    		int temp = Inversex;
    		Inversex = Inversey;
    		Inversey = temp+ - (a/m)*Inversey;
    	}
    }
    static long mod1 = 1000000007;
    static long mod2 = 1000000009;
	public static long gcd(long a,long b){
		if(a%b==0)
			return b;
		return gcd(b,a%b);
	}
	public static boolean isPrime(long a){
		if(a==1)
			return false;
		else if(a==2||a==3)
			return true;
		for(long i=2;i<=Math.sqrt(a);i++)
			if(a%i==0)
				return false;
		return true;
	}
	public static double distance(int a,int b,int x,int y){
		return Math.sqrt(((long)(a-x)*(long)(a-x))+((long)(b-y)*(long)(b-y)));
	}
	public static class Pair implements Comparable<Pair> {
		long u;
		long v;
		BigInteger bi;
		public Pair(long u, long v) {
			this.u = u;
			this.v = v;
		}
		public int hashCode() {
			int hu = (int) (u ^ (u >>> 32));
			int hv = (int) (v ^ (v >>> 32));
			return 31 * hu + hv;
		}
		public boolean equals(Object o) {
			Pair other = (Pair) o;
			return u == other.u && v == other.v;
		}
		public int compareTo(Pair other) {
			return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v);
		}
		public String toString() {
			return "[u=" + u + ", v=" + v + "]";
		}
	}
	public static int seive(int a[],boolean b[]){
		int count = 0;
		for(int i=2;i<a.length;i++){
			if(!b[i]){
				for(int j=2*i;j<a.length;j=j+i)
					b[j] = true;
				a[count++] = i;
			}
		}
		return count;
	}
	private static void soln(){
		int n = nI();
		int arr[] = new int[n];
		int a[] = new int[n];
		for(int i=0;i<n;i++){
			arr[i] = nI()-1;
			a[i] = arr[i];
		}
		int i = 0,counter = 0;
		long t = 1;
		boolean b[] = new boolean[n];
		for(i=0;i<n;i++){
			int j = 0;
			for(j=0;j<n;j++){
				if(j==arr[arr[j]]&&!(b[j]&&b[arr[arr[j]]])){
					t = (t*(i+1))/gcd(t,i+1);
					if(!b[j]){
						counter++;
						b[j] = true;
					}
					else if(!b[arr[arr[j]]]){
						counter++;
						b[arr[arr[j]]] = true;
					}
				}
			}
			for(j=0;j<n;j++)
				arr[j] = a[arr[j]];
		}
		if(counter==n)
			pw.println(t);
		else
			pw.println("-1");
			/*int n = nI();
			int arr[] = new int[n];
			for(int i=0;i<n;i++)
				arr[i] = nI();
			int dp[] = new int[n];
			HashMap h = new HashMap();
			for(int i=0;i<n;i++){
				if(arr[i]==2||arr[i]==3){
					if(h.containsKey(arr[i])){
						dp[i] = Math.max(dp[i],(int)h.get(arr[i])+1);
						h.put(arr[i], dp[i]);
					}
					else{
						dp[i] = Math.max(dp[i],1);
						h.put(arr[i], dp[i]);
					}
					continue;
				}
				for(int j=1;j<=Math.sqrt(arr[i]);j++){
					if(arr[i]%j==0){
						if(h.containsKey(j)&&j!=1){
							dp[i] = Math.max(dp[i],(int)h.get(j)+1);
							h.put(j, dp[i]);
						}
						else if(j!=1){
							dp[i] = Math.max(dp[i],1);
							h.put(j, dp[i]);
						}
						if(j*j!=arr[i]){
							if(h.containsKey(arr[i]/j)){
								dp[i] = Math.max(dp[i],(int)h.get(arr[i]/j)+1);
								h.put(arr[i]/j, dp[i]);
							}
							else{
								dp[i] = Math.max(dp[i],1);
								h.put(arr[i]/j, dp[i]);
							}
						}
					}
				}
			}
			int max = 0;
			for(int i=0;i<n;i++){
				if(max<dp[i])
					max = dp[i];
			}
			pw.println(Math.max(max,1));*/
	}
	public static void main(String[] args) {
		InputReader(System.in);
		pw = new PrintWriter(System.out);
		soln();
		pw.close();
	}
	// To Get Input
	// Some Buffer Methods
	public static void InputReader(InputStream stream1) {
		stream = stream1;
	}
	private static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}
	private static boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
	private static int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}
	private static int nI() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}
	private static long nL() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}
	private static String nextToken() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}
	private static String nLi() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}
	private static int[] nextIntArray(int n) {
		int[] arr = new int[n];
		for (int i = 0; i < n; i++)
			arr[i] = nI();
		return arr;
	}
	private static long[] nextLongArray(int n) {
		long[] arr = new long[n];
		for (int i = 0; i < n; i++)
			arr[i] = nL();
		return arr;
	}
	private static void pArray(int[] arr) {
		for (int i = 0; i < arr.length; i++)
			System.out.print(arr[i] + " ");
		System.out.println();
		return;
	}
	private static void pArray(long[] arr) {
		for (int i = 0; i < arr.length; i++)
			System.out.print(arr[i] + " ");
		System.out.println();
		return;
	}
	private static boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}
	private interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author zodiacLeo
 */
public class Main
{
    public static void main(String[] args)
    {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        FastPrinter out = new FastPrinter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA
    {
        private int INF = ((int) 1e7);

        public void solve(int testNumber, FastScanner in, FastPrinter out)
        {
            int n = in.nextInt();
            int[][] g = new int[n][n];

            for (int i = 0; i < n; i++)
            {
                Arrays.fill(g[i], INF);
            }
            for (int i = 0; i < n; i++)
            {
                int to = in.nextInt() - 1;
                g[i][to] = 1;
            }

            for (int k = 0; k < n; k++)
            {
                for (int i = 0; i < n; i++)
                {
                    for (int j = 0; j < n; j++)
                    {
                        g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]);
                    }
                }
            }
            long L = 1;
            long res = -1;
            for (int i = 0; i < n; i++)
            {
                if (g[i][i] == INF)
                {
                    out.println(-1);
                    return;
                }
                L = lcm(L, g[i][i]);
            }
            res = L;
            if (res % 2 == 0)
            {
                out.println(res / 2);
                return;
            }
            out.println(res);
        }

        private long lcm(long a, long b)
        {
            return a / gcd(a, b) * b;
        }

        private long gcd(long a, long b)
        {
            return b == 0 ? a : gcd(b, a % b);
        }

    }

    static class FastPrinter extends PrintWriter
    {
        public FastPrinter(OutputStream out)
        {
            super(out);
        }

        public FastPrinter(Writer out)
        {
            super(out);
        }

    }

    static class FastScanner
    {
        public BufferedReader br;
        public StringTokenizer st;

        public FastScanner(InputStream is)
        {
            br = new BufferedReader(new InputStreamReader(is));
        }

        public FastScanner(File f)
        {
            try
            {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
        }

        public String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                String s = null;
                try
                {
                    s = br.readLine();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
                if (s == null)
                    return null;
                st = new StringTokenizer(s);
            }
            return st.nextToken();
        }

        public int nextInt()
        {
            return Integer.parseInt(next());
        }

    }
}

/**
 * Created by Bakytzhan_Manaspayev on 1/6/2017.
 */
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;

public class AnotherCandidate {

    static PrintStream out = System.out;

    static void solve() throws IOException {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        int[] a = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            a[i] = in.nextInt();
        }

        boolean[] used = new boolean[n + 1];
        ArrayList<Integer> list = new ArrayList<>();

        for (int i = 1; i <= n; i++) {
            if (used[i]) continue;
            used[i] = true;

            int size = 1;
            int next = a[i];
            while (i != next) {
                if (used[next]) {
                    out.println(-1);
                    return;
                }
                used[next] = true;
                size++;
                next = a[next];
            }
            if (size % 2 == 1) {
                list.add(size);
            } else {
                list.add(size / 2);
            }
        }

        int ans = 1;
        for (int i = 0; i < list.size(); i++) {
            ans = lcm(ans, list.get(i));
        }

        out.println(ans);
    }

    static int gcd(int a, int b) {
        return a == 0 ? b : gcd(b % a, a);
    }

    static int lcm(int a, int b) {
        return a / gcd(a, b) * b;
    }

    public static void main(String[] args) throws IOException {
        solve();
    }
}

import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.regex.*;
public class Myclass{
         public static ArrayList a[]=new ArrayList[300001];
         static boolean visited[]=new boolean [300001];
         static boolean chk;
         static int start;
         static int cnt;
         static void dfs(int n) {
        	 visited[n]=true;
			 cnt++;
        	 for(int i=0;i<a[n].size();i++) {
        		 int id=(int) a[n].get(i);
        		 if(!visited[id]) {
        			 dfs(id);
        		 }
        		 else if (visited[id] && id==start) {
        			 chk=true;
        		 }

        	 }
         }
         static void pre(int i) {
        	 start=i;
        	 chk=false;
        	 cnt=0;
         }

		public static void main(String[] args)
        {
            InputReader in = new InputReader(System.in);
            PrintWriter pw = new PrintWriter(System.out);
            int n=in.nextInt();

            for(int i=0;i<=n;i++)
            	a[i]=new ArrayList<Integer>();
            for(int i=1;i<=n;i++) {
            	int x=in.nextInt();
            	a[i].add(x);
            }

            int ans=1;
            for(int i=1;i<=n;i++) {
            	if(!visited[i]) {
            		pre(i);
            		dfs(i);
            		if(!chk) {
            			pw.println(-1);
            			pw.flush();
            			pw.close();
            			System.exit(0);
            		}
            		else
            		{
            			if(cnt%2==0) {
            				ans=LCM(ans,cnt/2);
            			}
            			else
            				ans=LCM(ans,cnt);
            		}
            	}
            }
            pw.println(ans);
            pw.flush();
            pw.close();

        }

		private static void debug(Object... o) {
			System.out.println(Arrays.deepToString(o));
		}
        static class InputReader
        {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }
        public int snext()
        {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars)
            {
                curChar = 0;
                try
                {
                    snumChars = stream.read(buf);
                }

                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt()
        {
            int c = snext();
            while (isSpaceChar(c))
            {
                c = snext();
            }
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = snext();
            }
            int res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong()
        {
            int c = snext();
            while (isSpaceChar(c))
            {
                c = snext();
            }
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = snext();
            }
            long res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n)
        {
            int a[] = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = nextInt();
            }
            return a;
        }
        static class tri implements Comparable<tri> {
            int p, c, l;

            tri(int p, int c, int l) {
                this.p = p;
                this.c = c;
                this.l = l;
            }

            public int compareTo(tri o) {
                return Integer.compare(l, o.l);
            }
        }

        public String readString()
        {
            int c = snext();
            while (isSpaceChar(c))
            {
                c = snext();
            }
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = snext();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public String nextLine()
        {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = snext();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c)
        {
            return c == '\n' || c == '\r' || c == -1;
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }
        public static long mod = 1000000007;
        public static int d;
        public static int p;
        public static int q;

        public static int[] suffle(int[] a,Random gen)
        {
            int n = a.length;
            for(int i=0;i<n;i++)
            {
                int ind = gen.nextInt(n-i)+i;
                int temp = a[ind];
                a[ind] = a[i];
                a[i] = temp;
            }
            return a;
        }

        public static void swap(int a, int b){
            int temp = a;
            a = b;
            b = temp;
        }

       /* public static long primeFactorization(long n)
        {
             HashSet<Integer> a =new HashSet<Integer>();
        	long cnt=0;
            for(int i=2;i*i<=n;i++)
            {
                while(a%i==0)
                {
                    a.add(i);
                    a/=i;
                }
            }
            if(a!=1)
            	cnt++;
                //a.add(n);
            return cnt;
        }*/

        public static void sieve(boolean[] isPrime,int n)
        {
            for(int i=1;i<n;i++)
                isPrime[i] = true;

            isPrime[0] = false;
            isPrime[1] = false;

            for(int i=2;i*i<n;i++)
            {
                if(isPrime[i] == true)
                {
                    for(int j=(2*i);j<n;j+=i)
                        isPrime[j] = false;
                }
            }
        }

        public static int GCD(int a,int b)
        {
            if(b==0)
                return a;
            else
                return GCD(b,a%b);
        }

        public static long GCD(long a,long b)
        {
            if(b==0)
                return a;
            else
                return GCD(b,a%b);
        }

        public static void extendedEuclid(int A,int B)
        {
            if(B==0)
            {
                d = A;
                p = 1 ;
                q = 0;
            }
            else
            {
                extendedEuclid(B, A%B);
                int temp = p;
                p = q;
                q = temp - (A/B)*q;
            }
        }

        public static long LCM(long a,long b)
        {
            return (a*b)/GCD(a,b);
        }

        public static int LCM(int a,int b)
        {
            return (a*b)/GCD(a,b);
        }

        public static int binaryExponentiation(int x,int n)
        {
            int result=1;
            while(n>0)
            {
                if(n % 2 ==1)
                    result=result * x;
                x=x*x;
                n=n/2;
            }
            return result;
        }

        public static long binaryExponentiation(long x,long n)
        {
            long result=1;
            while(n>0)
            {
                if(n % 2 ==1)
                    result=result * x;
                x=x*x;
                n=n/2;
            }
            return result;
        }

        public static int modularExponentiation(int x,int n,int M)
        {
            int result=1;
            while(n>0)
            {
                if(n % 2 ==1)
                    result=(result * x)%M;
                x=(x%M*x)%M;
                n=n/2;
            }
            return result;
        }

        public static long modularExponentiation(long x,long n,long M)
        {
            long result=1;
            while(n>0)
            {
                if(n % 2 ==1)
                    result=(result%M * x%M)%M;
                x=(x%M * x%M)%M;
                n=n/2;
            }
            return result;
        }

        public static long modInverse(int A,int M)
        {
            return modularExponentiation(A,M-2,M);
        }

        public static long modInverse(long A,long M)
        {
            return modularExponentiation(A,M-2,M);
        }

        public static boolean isPrime(int n)
        {

            if (n <= 1)  return false;
            if (n <= 3)  return true;

            if (n%2 == 0 || n%3 == 0)
                return false;

            for (int i=5; i*i<=n; i=i+6)
            {
                if (n%i == 0 || n%(i+2) == 0)
                   return false;
            }

            return true;
        }

         public static long[] shuffle(long[] a, Random gen){
                for(int i = 0, n = a.length;i < n;i++){
                    int ind = gen.nextInt(n-i)+i;
                    long d = a[i];
                    a[i] = a[ind];
                    a[ind] = d;
                }
                return a;
            }
        static class pair implements Comparable<pair>
        {
            Long x;
            Long y;
            pair(long a,long sum)
            {
                this.x=a;
                this.y=sum;
            }

		public int compareTo(pair o) {
                int result = x.compareTo(o.x);
                if(result==0)
                    result = y.compareTo(o.y);

            return result;
            }

            public String toString()
            {
                return x+" "+y;
            }

            public boolean equals(Object o)
            {
                if (o instanceof pair)
                {
                    pair p = (pair)o;
                    return p.x == x && p.y == y ;
                }
                return false;
            }

            public int hashCode()
            {
                return new Long(x).hashCode()*31 + new Long(y).hashCode();
            }
        }

}
class query {
	Long x;
	Integer y,z;
	query(long x,int y,int z){
		this.x=x;
		this.y=y;
		this.z=z;
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.Writer;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Niyaz Nigmatullin
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        FastPrinter out = new FastPrinter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, FastScanner in, FastPrinter out) {
            int n = in.nextInt();
            int[] a = in.readIntArray(n);
            for (int i = 0; i < n; i++) --a[i];
            boolean[] has = new boolean[n];
            for (int i = 0; i < n; i++) {
                if (has[a[i]]) {
                    out.println(-1);
                    return;
                }
                has[a[i]] = true;
            }
            long ans = 1;
            boolean[] was = new boolean[n];
            for (int i = 0; i < n; i++) {
                if (was[i]) continue;
                int count = 0;
                int v = i;
                while (!was[v]) {
                    was[v] = true;
                    ++count;
                    v = a[v];
                }
                if (count % 2 == 0) count /= 2;
                ans = MathUtils.lcm(ans, count);
            }
            out.println(ans);
        }

    }

    static class MathUtils {
        public static long gcd(long a, long b) {
            if (a < 0) a = -a;
            if (b < 0) b = -b;
            while (b != 0) {
                long t = a % b;
                a = b;
                b = t;
            }
            return a;
        }

        public static long lcm(long a, long b) {
            return a / gcd(a, b) * b;
        }

    }

    static class FastScanner extends BufferedReader {
        public FastScanner(InputStream is) {
            super(new InputStreamReader(is));
        }

        public int read() {
            try {
                int ret = super.read();
//            if (isEOF && ret < 0) {
//                throw new InputMismatchException();
//            }
//            isEOF = ret == -1;
                return ret;
            } catch (IOException e) {
                throw new InputMismatchException();
            }
        }

        static boolean isWhiteSpace(int c) {
            return c >= 0 && c <= 32;
        }

        public int nextInt() {
            int c = read();
            while (isWhiteSpace(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int ret = 0;
            while (c >= 0 && !isWhiteSpace(c)) {
                if (c < '0' || c > '9') {
                    throw new NumberFormatException("digit expected " + (char) c
                            + " found");
                }
                ret = ret * 10 + c - '0';
                c = read();
            }
            return ret * sgn;
        }

        public String readLine() {
            try {
                return super.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        public int[] readIntArray(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextInt();
            }
            return ret;
        }

    }

    static class FastPrinter extends PrintWriter {
        public FastPrinter(OutputStream out) {
            super(out);
        }

        public FastPrinter(Writer out) {
            super(out);
        }

    }
}

import java.util.Scanner;

public class ArpasLoudOwf {
	static int n;
	static int crush[];
	static boolean vis[];
	public static int getCycle(int curNode,int index,int step)
	{
		if (index==curNode && step!=0)
			return step;
		if (vis[curNode])
			return -1;
		vis[curNode] = true;
		int res = getCycle(crush[curNode], index, step+1);
		vis[curNode] = false;
		return res;
	}
	public static long lcm(long lcm,int b)
	{
		return 1L*lcm*b/gcd(lcm,b);
	}
	public static long gcd(long lcm,long l)
	{
		return l == 0 ? lcm : gcd(l, lcm % l);
	}
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		crush = new int[n];
		vis = new boolean[n];
		for (int i=0;i<n;i++)
			crush[i] = sc.nextInt()-1;
		long lcm = 1;
		for (int i=0;i<n;i++)
		{
			int x = getCycle(i,i,0);
			if (x==-1)
			{
				System.out.println(x);
				return;
			}
			if (x%2==0)
				x/=2;
			lcm = lcm(lcm,x);
		}
		System.out.println(lcm);
	}
}

import java.util.*;
import java.io.*;
import java.util.Queue;
public class W27Q2 {

	public static void main(String[] args){
		// TODO Auto-generated method stub

		InputReader in = new InputReader(System.in);
	        PrintWriter w = new PrintWriter(System.out);

	        int n = in.nextInt();
			int[] crush = new int[n+1];
			boolean[] check = new boolean[n+1];

			for(int i = 1;i<=n;i++){
				int tmp = in.nextInt();
				crush[i] = tmp;
				if(check[tmp]==true){
					w.println(-1);
					w.close();
					return;
				}else{
					check[tmp] = true;
				}
			}

			boolean[] cycle = new boolean[n+1];
			long ans = 1;
			for(int i = 1;i<=n;i++){
				if(cycle[i])
					continue;
				cycle[i] = true;
				int cl = 1;
				for(int j = crush[i];!cycle[j];j = crush[j]){
					cl++;
					cycle[j]=true;
				}
				if((cl%2==0))
					cl/=2;
				ans = in.lcm(cl, ans);
			}
			w.println(ans);
			w.close();
		}

 	static class  InputReader {

       private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int snext() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

        public String readString() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = snext();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public String nextLine() {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = snext();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
        public long gcd(long a, long b) {
    		return b == 0 ? a : gcd(b, a % b);
    	}

    	public long lcm(long a, long b) {
    		return a * b / (gcd(a, b));
    	}
    }

}

import java.io.*;
import java.util.*;
import java.lang.*;

public class Rextester{
    private int[] graph;
    private int V;
    public Rextester(int V,int[] array){
        this.V = V;
        graph = new int[V];
        for(int i=0;i<V;i++){
            graph[i]=array[i];
        }
    }

    public int findCycle(int s){
        int count=0,i=s;
        boolean[] visited = new boolean[V];
        while(true){
            if(visited[i]&&s==i){
                if(count%2==0){
                    return count/2;
                }
                return count;
            }
            else if(visited[i]&&s!=i){
                return -1;
            }
            else{
                visited[i]=true;
                i=graph[i];
                count++;
            }
        }
    }

    public long findMin(){
        int[] array = new int[10000];
        int p=0;
        for(int i=0;i<V;i++){
                int x = findCycle(i);
                if(x==-1){
                    return -1;
                }
                else{
                    array[p++]=x;
                }
        }
        return LCM(array,p);
    }

    public long LCM(int[] array,int p){
        long lcm = LCM(array[0],array[1]);
        for(int i=2;i<p;i++){
            lcm=LCM(lcm,array[i]);
        }
        return lcm;
    }

    public long LCM(long a,long b){
        long m = a*b;
        long hcf = HCF(a,b);
        return m/hcf;
    }

    public long HCF(long a,long b){
        if(a%b==0){
            return b;
        }
        return HCF(b,a%b);
    }

    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = new Integer(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());
        br.close();
        int[] array = new int[n];
        for(int i=0;i<n;i++){
            array[i]=new Integer(st.nextToken())-1;
        }
        Rextester rs = new Rextester(n,array);
        System.out.println(rs.findMin());
    }
}

import java.awt.Point;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Comparator;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

public class Easy {
    static long mod = (long) (1e9 + 7);
    static int[] dx = {1,-1,0,0};
    static int[] dy = {0,0,1,-1};
    static int[] ddx = {1,-1,0,0,1,-1,1,-1};
    static int[] ddy = {0,0,1,-1,1,-1,-1,1};

    static int[] fact = new int[101];
    public static void main(String[] args) {
        MyScanner sc = new MyScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out));
        int n = sc.nextInt();
        int[] e = new int[n];
        computeFact();
        for (int i = 0; i < e.length; i++) {
            e[i] = sc.nextInt() - 1;
        }
        HashSet<Integer> loops = new HashSet<>();
        boolean[] trav = new boolean[n];
        boolean failed = false;
        for (int i = 0; i < n; i++) {
            if (!trav[i]) {
                int curr = e[i];
                int size = 1;
                trav[i] = true;
                while (!trav[curr]) {
                    trav[curr] = true;
                    size++;
                    curr = e[curr];
                }
                if (curr == i) {
                    if (size % 2 == 0) {
                        loops.add(size/2);
                    } else {
                        loops.add(size);
                    }
                } else {
                    failed = true;
                }
            }
        }
        if (failed) {
            out.println(-1);
        } else {
            int[] factors = new int[101];
            int[] cf = new int[101];
            for (int curr : loops) {
                Arrays.fill(cf, 0);
                while (curr > 1) {
                    cf[fact[curr]]++;
                    curr /= fact[curr];
                }
                for (int i = 0; i < cf.length; i++) {
                    //System.out.print(cf[i] + ",");
                    factors[i] = Math.max(factors[i], cf[i]);
                }
                //System.out.println();
            }
            long ans = 1;
            for (int i = 1; i < factors.length; i++) {
                //System.out.print(factors[i] + ",");
                ans *= Math.pow(i, factors[i]);
            }
            //System.out.println();
            out.println(ans);
        }
        out.close();
    }

    public static void computeFact() {
        fact[1] = 1;
        fact[0] = 1;
        for (int i = 2; i < fact.length; i++) {
            if (fact[i] == 0) {
                //fact[i] = i;
                for (int j = i; j < fact.length; j += i) {
                    if (fact[j] == 0) fact[j] = i;
                }
            }
        }
        /*for (int i = 0; i < fact.length; i++) {
            System.out.print(fact[i] + ",");
        }
        System.out.println();*/
    }

    public static class Node {
        ArrayList<Integer> edges;
        boolean t;
        int p;
        long pw;

        public Node() {
            edges = new ArrayList<>();
        }
    }

    public static class MaxSTree {

        int n;
        int[] tmax;
        int[] tadd; // tadd[i] affects tmax[i], tadd[2*i+1] and tadd[2*i+2]

        void push(int root) {
            tmax[root] += tadd[root];
            tadd[2 * root + 1] += tadd[root];
            tadd[2 * root + 2] += tadd[root];
            tadd[root] = 0;
        }

        public MaxSTree(int n) {
            this.n = n;
            tmax = new int[4 * n];
            tadd = new int[4 * n];
        }

        public int get (int i) {
            return tmax[i];
        }

        public int max(int from, int to) {
            return max(from, to, 0, 0, n - 1);
        }

        int max(int from, int to, int root, int left, int right) {
            if (from == left && to == right) {
                return tmax[root] + tadd[root];
            }
            push(root);
            int mid = (left + right) >> 1;
                int res = Integer.MIN_VALUE;
                if (from <= mid)
                    res = Math.max(res, max(from, Math.min(to, mid), 2 * root + 1, left, mid));
                else if (to > mid)
                    res = Math.max(res, max(Math.max(from, mid + 1), to, 2 * root + 2, mid + 1, right));
                return res;
        }

        public void add(int from, int to, int delta) {
            add(from, to, delta, 0, 0, n - 1);
        }

        void add(int from, int to, int delta, int root, int left, int right) {
            if (from == left && to == right) {
                tadd[root] += delta;
                return;
            }
            // push can be skipped for add, but is necessary for other operations such as set
            push(root);
            int mid = (left + right) >> 1;
            if (from <= mid)
                add(from, Math.min(to, mid), delta, 2 * root + 1, left, mid);
            if (to > mid)
                add(Math.max(from, mid + 1), to, delta, 2 * root + 2, mid + 1, right);
            tmax[root] = Math.max(tmax[2 * root + 1] + tadd[2 * root + 1], tmax[2 * root + 2] + tadd[2 * root + 2]);
        }
    }

    public static class STree {
        long[] tree;
        long[] base;

        public STree(long[] base) {
            this.base = base;
            tree = new long[2 * base.length];
            for (int i = base.length; i < tree.length; i++) {
                tree[i] = base[i - base.length];
            }
            for (int i = base.length - 1; i > 0; i--) {
                tree[i] = tree[2*i] + tree[2*i ^ 1];
            }
        }

        public long get(int index) {
            return tree[index + base.length];
        }

        public void modify(int index, long val) {
            index += base.length;
            tree[index] = val;
            while (index > 1) {
                tree[index/2] = tree[index] + tree[index ^ 1];
                index/=2;
            }
        }

        public long query(int start, int end) {
            long ans = 0;
            start += base.length;
            end += base.length + 1;
            while (start < end) {
                if ((start & 1) == 1) {
                    ans += tree[start++];
                }
                if ((end & 1) == 1) {
                    ans += tree[--end];
                }
                start>>=1;
            end>>=1;
            }
            return ans;
        }

        public void print() {
            out.println();
            for (int i = base.length; i < tree.length; i++) {
                out.print(tree[i] + " ");
            }
            out.println();
        }
    }

    public static PrintWriter out;
    /*
    int n      = sc.nextInt();        // read input as integer
    long k     = sc.nextLong();       // read input as long
    double d   = sc.nextDouble();     // read input as double
    String str = sc.next();           // read input as String
    String s   = sc.nextLine();       // read whole line as String
    out.println(result);              // print via PrintWriter
     */
    public static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine(){
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class C implements Runnable {
	BufferedReader in;
	PrintWriter out;
	StringTokenizer tok = new StringTokenizer("");

	public static void main(String[] args) {
		new Thread(new C()).run();
	}

	@Override
	public void run() {
		init();
		solve();
		out.close();
	}

	private int readInt() {
		return Integer.parseInt(readString());
	}

	private void init() {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
	}

	private String readString() {
		while (!tok.hasMoreTokens()) {
			try {
				tok = new StringTokenizer(in.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return tok.nextToken();
	}

	private long readLong() {
		return Long.parseLong(readString());
	}

	private void solve() {
		int n = readInt();
		int[] graph = new int[n];
		for (int i = 0; i < n; i++) {
			graph[i] = readInt() - 1;
		}
		used = new boolean[n];

		for (int i = 0; i < n; i++) {
			if (!used[i]) {
				dfs(0, i, i, graph);
			}
		}
		if (flag) {
			out.print(-1);
		} else {
			long ans = 1;
			for (int i = 0; i < sizes.size(); i++) {
				if (sizes.get(i) % 2 == 0) {
					sizes.set(i, sizes.get(i) / 2);
				}
				ans = (ans * sizes.get(i)) / gcd(ans, sizes.get(i));
			}
			out.print(ans);
		}
	}

	boolean flag = false;
	boolean[] used;
	ArrayList<Integer> sizes = new ArrayList<>();

	private void dfs(int count, int start, int v, int[] gr) {
		if (used[v]) {
			if (v == start) {
				sizes.add(count);
			} else {
				flag = true;
			}
			return;
		} else {
			used[v] = true;
			dfs(count + 1, start, gr[v], gr);
		}

	}

	private long gcd(long a, long b) {
		if (b == 0)
			return a;
		else
			return gcd(b, a % b);
	}

}

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.NoSuchElementException;

public class C {

	static final int INF = (int)1e9 + 7;

	int n;
	int[] c;
	boolean[] used;

	public int isClosedPath(int now,int goal,int t){

		if(now == goal && used[now]){
			return t % 2 == 0 ? t / 2 : t;
		}

		if(used[now])return INF;
		used[now] = true;
		return isClosedPath(c[now],goal,t + 1);
	}

	public long gcd(long x,long y){
		return y == 0 ? x : gcd(y,x%y);
	}

	public long lcm(long x,long y){
		return x * y / gcd(x,y);
	}

	public void solve() {
		n = nextInt();
		c = new int[n];
		used = new boolean[n];
		for(int i = 0;i < n;i++){
			c[i] = nextInt() - 1;
		}

		long ans = 1;

		for(int i = 0;i < n;i++){
			Arrays.fill(used, false);
			used[i] = true;
			int ret = isClosedPath(c[i],i,1);

			if(ret == INF){
				out.println(-1);
				return;
			}

			ans = lcm(ans,ret);
		}

		out.println(ans);
	}

	public static void main(String[] args) {
		out.flush();
		new C().solve();
		out.close();
	}

	/* Input */
	private static final InputStream in = System.in;
	private static final PrintWriter out = new PrintWriter(System.out);
	private final byte[] buffer = new byte[2048];
	private int p = 0;
	private int buflen = 0;

	private boolean hasNextByte() {
		if (p < buflen)
			return true;
		p = 0;
		try {
			buflen = in.read(buffer);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (buflen <= 0)
			return false;
		return true;
	}

	public boolean hasNext() {
		while (hasNextByte() && !isPrint(buffer[p])) {
			p++;
		}
		return hasNextByte();
	}

	private boolean isPrint(int ch) {
		if (ch >= '!' && ch <= '~')
			return true;
		return false;
	}

	private int nextByte() {
		if (!hasNextByte())
			return -1;
		return buffer[p++];
	}

	public String next() {
		if (!hasNext())
			throw new NoSuchElementException();
		StringBuilder sb = new StringBuilder();
		int b = -1;
		while (isPrint((b = nextByte()))) {
			sb.appendCodePoint(b);
		}
		return sb.toString();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}

	public long nextLong() {
		return Long.parseLong(next());
	}

	public double nextDouble() {
		return Double.parseDouble(next());
	}
}

import java.util.Arrays;
import java.util.Scanner;

public class Owf {
	static int[] a;
	static int[] cycle;
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		int n=scan.nextInt();
		a=new int[n];
		for(int i=0;i<n;i++) a[i]=scan.nextInt()-1;
		cycle=new int[n];

		//a[i] = length of cycle from i (-1 = no cycle from there)
		Arrays.fill(cycle,-1);
		for(;ind<n;ind++) dfs(ind,0,new boolean[n]);
//		System.out.println(Arrays.toString(cycle));

		for(int i=0;i<n;i++) if(cycle[i]%2==0)cycle[i]/=2;

		long res=1;
		for(int i:cycle) {
			if(i==-1) {
				System.out.println(-1);
				return;
			}
			res=res*i/gcd(res,i);
		}
		System.out.println(res);
	}
	public static long gcd(long a, long b) {
		return b==0?a:gcd(b,a%b);
	}
	static int ind;
	public static void dfs(int n, int ct, boolean[] v) {
		if(v[n]&&n==ind) {
			cycle[n]=ct;
			return;
		}
		else if(v[n]) return;
		v[n]=true;
		dfs(a[n],ct+1,v);
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        int n;
        int[] next;
        int[] color;
        int[] parent;
        List<Integer> sizes;
        boolean[] inCycle;

        public void solve(int testNumber, InputReader in, PrintWriter out) {

            n = in.nextInt();
            next = new int[n];
            sizes = new ArrayList<>();
            parent = new int[n];
            Arrays.fill(parent, -1);
            inCycle = new boolean[n];
            color = new int[n];
            Arrays.fill(color, -1);
            for (int i = 0; i < n; i++) {
                next[i] = in.nextInt() - 1;
            }
            for (int i = 0; i < n; i++) {
                if (color[i] == -1) {
                    dfs(i);
                }
            }
            for (int i = 0; i < n; i++) {
                if (!inCycle[i]) {
                    out.println(-1);
                    return;
                }
            }
            long p = 1;
            for (int size : sizes) {
                if (size % 2 == 0)
                    size /= 2;
                p = lcm(p, size);
            }
            out.println(p);
        }

        private long gcd(long a, long b) {
            return (b == 0) ? a : gcd(b, a % b);
        }

        private long lcm(long a, long b) {
            return a / gcd(a, b) * b;
        }

        private void dfs(int v) {
            color[v] = 0;
            if (color[next[v]] == 0) {
                cycle(v, next[v]);
            } else {
                parent[next[v]] = v;
                dfs(next[v]);
            }
            color[v] = 1;
        }

        private void cycle(int v, int root) {
            int cur = v;
            int l = 1;
            inCycle[cur] = true;
            while (cur != root) {
                l++;
                cur = parent[cur];
                inCycle[cur] = true;
            }
            sizes.add(l);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.util.*;
import java.io.*;

public class Main
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int[] crushes = new int[Integer.parseInt(br.readLine())];
		boolean[] visited = new boolean[crushes.length];

		StringTokenizer st = new StringTokenizer(br.readLine());
		for (int i = 0; i < crushes.length; i++)
		{
			crushes[i] = Integer.parseInt(st.nextToken()) - 1;
		}

		int result = 1;
		boolean possible = true;

		for (int i = 0; i < crushes.length; i++)
		{
			if(!visited[i])
			{
				int cnt = 1;

				visited[i] = true;
				int idx = crushes[i];

				while(idx != i && !visited[idx])
				{
					visited[idx] = true;
					idx = crushes[idx];

					cnt++;
				}

				if(idx == i)
				{
					if(cnt % 2 == 0)
						cnt /= 2;

					result = lcm(result, cnt);
				}
				else
				{
					possible = false;
					break;
				}
			}
		}

		System.out.println(possible ? result : -1);
	}

	public static int lcm(int a, int b)
	{
		return a * b / gcd(a, b);
	}

	public static int gcd(int a, int b)
	{
		if(b == 0)
		{
			return a;
		}

		return gcd(b, a % b);
	}
}

import java.util.Scanner;

public class Solution {

    private static int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }

    private static int lcm(int a, int b) {
        int g = gcd(a, b);
        return a * (b / g);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] crush = new int[n];
        boolean[] inDegree = new boolean[n];
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
            if (inDegree[crush[i]]) {
                System.out.println(-1);
                return;
            }
            inDegree[crush[i]] = true;
        }
        boolean[] visited = new boolean[n];
        int answer = 1;

        for (int i = 0; i < n; i++) {
            if (visited[i])
                continue;
            int j = i;
            int length = 0;
            while (!visited[j]) {
                visited[j] = true;
                j = crush[j];
                length += 1;
            }
            if (length % 2 == 0)
                answer = lcm(answer, length / 2);
            else
                answer = lcm(answer, length);
        }

        System.out.println(answer);
    }
}

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

public class CF_741A {
	public static void main(String[] args) {
		new CF_741A().run();
	}
	public void run(){
		FastScanner sc = new FastScanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		int n = sc.nextInt();
		DSU dsu = new DSU(n);

		boolean[] vis = new boolean[n+1];
		boolean isFinish = false;
		//构造并查集
		for(int i = 0;i<n;i++){
			int tmp = sc.nextInt();
			if(vis[tmp]){
				isFinish = true;
			}
			vis[tmp] = true;
			dsu.union(i, tmp-1);
		}
		if(isFinish){
			out.println(-1);
			out.close();
			return ;
		}
		long res = 1;
		for(int i = 0;i<n;i++){
			if(dsu.get(i)!=i)
				continue;
			int len = 0;
			for(int j = 0;j<n;j++){
				if(dsu.get(j)==i)
					len++;
			}
			if((len&1)==0)
				len>>=1;
			res = sc.lcm(res, len);
		}
		out.println(res);
		out.close();
	}
}
class FastScanner {
	public BufferedReader br;
	public StringTokenizer st;

	public FastScanner(InputStream in) {
		br = new BufferedReader(new InputStreamReader(in));
		st = null;
	}

	public boolean hasMoreTokens() {
		while (st == null || !st.hasMoreTokens()) {
			String line = null;
			try {
				line = br.readLine();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (line == null)
				return false;
			st = new StringTokenizer(line);
		}
		return true;
	}

	public String next() {
		if (!hasMoreTokens())
			return null;
		return st.nextToken();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}

	public long nextLong() {
		return Long.parseLong(next());
	}

	//读一个int类型的数组
	public int[] readIntArray(int n) {
		int[] array = new int[n];
		for (int i = 0; i < n; i++) {
			array[i] = nextInt();
		}
		return array;
	}

	//读一个long数组
	public long[] readLongArray(int n) {
		long[] array = new long[n];
		for (int i = 0; i < n; i++) {
			array[i] = nextLong();
		}
		return array;
	}

	//读一个字符串数组
	public String[] readStringArray(int n) {
		String[] a = new String[n];
		for (int i = 0; i < n; i++) {
			a[i] = next();
		}
		return a;
	}

	//打乱一个数组，便于排序
	public void shuffleIntArray(int[] a) {
		Random rand = new Random();
		for (int i = 0; i < a.length; i++) {
			int x = rand.nextInt(i + 1); // 0~i
			int t = a[i];
			a[i] = a[x];
			a[x] = t;
		}
	}

	// 只适合比较小的数，太大的数会越界
	public long factorial(long n) {
		if (n == 0)
			return 1L;
		long res = 1;
		for (long i = 2; i <= n; i++) {
			res *= i;
		}
		return res;
	}

	// 只适合比较小的数，太大的数会越界
	public long combination(long mom, long son) {
		return factorial(mom) / (factorial(son) * factorial(mom - son));
	}

	//求最小公倍数
	public long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	//求最大公约数
	public long lcm(long a, long b) {
		return a * b / (gcd(a, b));
	}

	//格式化double类型的数
	public double format(String pattern, double d) {
		DecimalFormat df = new DecimalFormat(pattern);
		return Double.parseDouble(df.format(d));
	}

	//判断一个数是否是2的指数
	public boolean isPowerOfTwo(long v) {
		return (v & (v - 1)) == 0;
	}
}
class DSU {
	int[] p;

	public DSU(int n) {
		p = new int[n];
		clear();
	}

	public void clear() {
		for (int i = 0; i < p.length; i++) {
			p[i] = i;
		}
	}

	public int get(int x) {
		int y = x;
		while (y != p[y]) {
			y = p[y];
		}
		// 压缩
		while (x != p[x]) {
			int t = p[x];
			p[x] = y;
			x = t;
		}
		return y;
	}

	public boolean union(int a, int b) {
		a = get(a);
		b = get(b);
		p[a] = b;
		return a != b;
	}

}

import java.util.*;
import java.io.*;

/**
 * @author Deepit-PC
 *
 */
public class ArpasLoudOwfAndMehrdadsEvilPlan {
    public static InputReader in;
    public static PrintWriter out;

    public static final int MOD = (int) (1e9 + 7);

    public static void main(String[] args) {
	in = new InputReader(System.in);
	out = new PrintWriter(System.out);

	int n = in.nextInt();
	int[] crush = new int[n + 1];
	for (int i = 1; i <= n; i++) {
	    crush[i] = in.nextInt();
	}

	boolean found = true;
	int[] cycle = new int[n + 1];
	boolean[] visited = new boolean[n + 1];
	for (int start = 1; start <= n; start++) {
	    visited = new boolean[n + 1];
	    int next = start;
	    while(!visited[next]) {
		visited[next] = true;
		next = crush[next];
		cycle[start]++;
	    }
	    if((cycle[start]&1) == 0) {
		cycle[start] /= 2;
	    }
	    if(next != start || cycle[start] == 0) {
		found = false;
		break;
	    }
	}
	//out.println(Arrays.toString(cycle));
	long ans = -1;
	if(found) {
	    ans = cycle[1];
	    for (int i = 2; i <= n; i++) {
		ans = (ans*cycle[i])/(gcd(cycle[i], ans));
	    }
	}
	out.println(ans);

	out.close();
    }

    public static long gcd(long x, long y) {
	if(y == 0) {
	    return x;
	}
	return gcd(y, x%y);
    }

    static class Node implements Comparable<Node> {
	int next;
	int dist;

	public Node(int u, int v) {
	    this.next = u;
	    this.dist = v;
	}

	public void print() {
	    out.println(next + " " + dist + " ");
	}

	public int compareTo(Node that) {
	    return Integer.compare(this.next, that.next);
	}
    }

    static class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[8192];
	private int curChar, snumChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
	    this.stream = stream;
	}

	public int snext() {
	    if (snumChars == -1)
		throw new InputMismatchException();
	    if (curChar >= snumChars) {
		curChar = 0;
		try {
		    snumChars = stream.read(buf);
		} catch (IOException e) {
		    throw new InputMismatchException();
		}
		if (snumChars <= 0)
		    return -1;
	    }
	    return buf[curChar++];
	}

	public int nextInt() {
	    int c = snext();
	    while (isSpaceChar(c))
		c = snext();
	    int sgn = 1;
	    if (c == '-') {
		sgn = -1;
		c = snext();
	    }
	    int res = 0;
	    do {
		if (c < '0' || c > '9')
		    throw new InputMismatchException();
		res *= 10;
		res += c - '0';
		c = snext();
	    } while (!isSpaceChar(c));
	    return res * sgn;
	}

	public long nextLong() {
	    int c = snext();
	    while (isSpaceChar(c))
		c = snext();
	    int sgn = 1;
	    if (c == '-') {
		sgn = -1;
		c = snext();
	    }
	    long res = 0;
	    do {
		if (c < '0' || c > '9')
		    throw new InputMismatchException();
		res *= 10;
		res += c - '0';
		c = snext();
	    } while (!isSpaceChar(c));
	    return res * sgn;
	}

	public int[] nextIntArray(int n) {
	    int a[] = new int[n];
	    for (int i = 0; i < n; i++)
		a[i] = nextInt();
	    return a;
	}

	public String readString() {
	    int c = snext();
	    while (isSpaceChar(c))
		c = snext();
	    StringBuilder res = new StringBuilder();
	    do {
		res.appendCodePoint(c);
		c = snext();
	    } while (!isSpaceChar(c));
	    return res.toString();
	}

	public boolean isSpaceChar(int c) {
	    if (filter != null)
		return filter.isSpaceChar(c);
	    return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public interface SpaceCharFilter {
	    public boolean isSpaceChar(int ch);
	}
    }
}

import java.io.*;
import java.util.*;

public class p741a {
    static class Pair
    {
        public int a,b;
        public Pair(int a, int b)
        {
            this.a=a;
            this.b=b;
        }
    }
    public static long hcf(long a, long b)
    {
        if(a==0 || b==0)
            return a+b;
        return hcf(b,a%b);
    }
    public static long lcm(long a, long b)
    {
        return (a*b)/hcf(a,b);
    }
	public static void main(String[] args)throws IOException {
        InputReader in = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = in.nextInt();
        int arr[] = new int[n];
        for(int i=0;i<n;i++)
            arr[i]=in.nextInt()-1;
        long rep[] = new long[n];
        Arrays.fill(rep,-1);
        long lc = 1;
		for(int i=0;i<n;i++)
        {
            int v=i;
            for(int j=0;j<n;j++)
            {
                v=arr[v];
                if(v==i)
                {
                    long val = ((j+1)%2!=0) ? (j+1) : (j+1)/(int)2;
                    // if((j+1))
                    // long val = (long)Math.min(1,(j+1)/(int)2);
                    rep[i]=val; lc=lcm(rep[i],lc);
                    break;
                }
            }
        }
        // for(int i=0;i<n;i++)
            // out.print(rep[i]+" ");
        // out.println();
        for(int i=0;i<n;i++)
        {
            // long val=-1;
            // if(rep[i]!=-1)
                // val = lc/rep[i];
            if(rep[i]==-1)
            {
                out.println(-1); out.close(); return;
            }
        }
        out.println(lc);
        out.close();
	}
    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

    }

}

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * Created by Shahjahan on 4/29/2017.
 * http://codeforces.com/contest/742/problem/C
 */
public class C {
    public static void main(String[] args) throws IOException {
        //BufferedReader br = new BufferedReader(new FileReader("F:\\Acm\\src\\input.txt"));
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());

        int crush[] = new int[n + 1];
        boolean[] mark = new boolean[n + 1];
        ArrayList<Integer> distances = new ArrayList<>(n + 1);

        String[] parts = br.readLine().split(" ");
        for (int i = 1; i <= n; i++) crush[i] = Integer.parseInt(parts[i - 1]);

        int x;
        for (x = 1; x <= n; x++) {
            int person = x;
            if (!mark[person] && person != crush[person]) {
                int count;
                for (count = 1; count <= n; count++) {
                    person = crush[person];
                    mark[person] = true;
                    if (person == x) break;
                }

                if (count > n) break;
                else distances.add(count % 2 == 0 ? count / 2 : count);
            }
        }

        if (x != n + 1) System.out.println(-1);
        else {
            ArrayList<Integer> primes = getSeivePrimes(n + 1);

            HashMap<Integer, Integer> primeCounter = new HashMap<>();
            for (int distance : distances) {
                for (int prime : primes) {
                    if (prime > distance) break;

                    int count;
                    for (count = 0; distance % prime == 0; count++) {
                        distance /= prime;
                    }

                    if (count > 0) {
                        Integer existingCount = primeCounter.get(prime);
                        if (existingCount == null || count > existingCount)
                            primeCounter.put(prime, count);
                    }
                }
            }

            long t = 1;
            for (Map.Entry<Integer, Integer> entry : primeCounter.entrySet()) {
                int prime = entry.getKey();
                int power = entry.getValue();
                t *= (long) Math.pow(prime, power);
            }

            System.out.println(t);
        }
    }

    private static ArrayList<Integer> getSeivePrimes(int n) {
        boolean[] isPrime = new boolean[n + 1];
        for (int i = 2; i <= n; i++) isPrime[i] = true;

        for (int factor = 2; factor * factor <= n; factor++) {
            if (isPrime[factor]) {
                for (int j = factor; factor * j <= n; j++) {
                    isPrime[factor * j] = false;
                }
            }
        }

        ArrayList<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= n; i++) {
            if (isPrime[i]) primes.add(i);
        }
        return primes;
    }
}

import java.util.*;
import java.math.BigInteger;

public class com {

	public static int prime[];
	public static boolean g[];
	public static int hs[];
	public static int a[];
	public static int nprime;

	public static void InitPrime() {
		for(int i = 2;  i <= 100;  i++) g[i] = true;
		nprime = 0;
		for(int i = 2;  i <= 100;  i++) if (g[i]) {
			int t = i * 2;
			while (t <= 100) {
				g[t] = false;
				t += i;
			}
			prime[++nprime] = i;
		}
	}

	public static void update(int value) {
		for(int i = 1;  i <= nprime;  i++) {
			int p = prime[i], s = 0;
			while (value % p == 0) {
				value /= p;  s++;
			}
			if (s > hs[i]) hs[i] = s;
		}
	}

	public static void main(String[] args) {
		prime = new int[222];
		a = new int[222];
		g = new boolean[222];
		hs = new int[222];

		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		for(int i = 1;  i <= n;  i++) {
			a[i] = sc.nextInt();
		}

		InitPrime();

		for(int i = 1;  i <= n;  i++) hs[i] = 0;
		for(int i = 1;  i <= n;  i++) g[i] = true;
		for(int i = 1;  i <= n;  i++) if (g[i]) {
			int x = i, first = i, ncount = 0;
			while (g[x]) {
				g[x] = false;
				x = a[x];
				ncount++;
			}
			if (x != first) {
				System.out.println(-1);
				return;
			}

			if (ncount % 2 == 0) ncount /= 2;
			update(ncount);
		}

		BigInteger ans = BigInteger.ONE;
		for(int i = 1;  i <= nprime;  i++) {
			for(int j = 1;  j <= hs[i];  j++) {
				ans = ans.multiply(BigInteger.valueOf(prime[i]));
			}
		}
		System.out.println(ans);
	}
}

//package round383;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.InputMismatchException;

public class A {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		int[] f = na(n);
		for(int i = 0;i < n;i++)f[i]--;
		boolean[] iif = new boolean[n];
		for(int i = 0;i < n;i++){
			iif[f[i]] = true;
		}
		for(int i = 0;i < n;i++){
			if(!iif[i]){
				out.println(-1);
				return;
			}
		}
		int[] cs = splitIntoCycleSizes(f);
		BigInteger cy = BigInteger.ONE;
		for(int v : cs){
			int w = v % 2 == 0 ? v / 2 : v;
			BigInteger W = BigInteger.valueOf(w);
			cy = cy.divide(cy.gcd(W)).multiply(W);
		}
		out.println(cy);
	}

	public static int[] splitIntoCycleSizes(int[] f)
	{
		int n = f.length;
		int[] szs = new int[n];
		boolean[] ved = new boolean[n];
		int q = 0;
		for(int i = 0;i < n;i++){
			if(!ved[i]){
				int p = 0;
				for(int cur = i;!ved[cur];cur = f[cur], p++)ved[cur] = true;
				szs[q++] = p;
			}
		}
		return Arrays.copyOf(szs, q);
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception { new A().run(); }

	private byte[] inbuf = new byte[1024];
	private int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}

import java.io.*;
import java.util.*;

public class Main {
    static FastScanner in;
    static int n;
    static int c[], ins[];
    static int ans = 1;
    static Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    public static void main(String[] args) throws IOException {
        //      Scanner in = new Scanner(new File("input.txt"));
        //        Scanner in = new Scanner(System.in);
        //        in = new FastScanner("input.txt");
        in = new FastScanner(System.in);
        n = in.nextInt();
        c = new int[n + 1];
        ins = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            c[i] = in.nextInt();
            ins[c[i]]++;
            map.put(i, c[i]);
        }
        for (int i = 1; i <= n; i++) {
            if (ins[i] != 1)
                ans = -1;
        }
        if (ans == -1) {
            System.out.println(ans);
        } else {
            ans = 1;
            boolean isVisited[] = new boolean[n + 1];
            for (int i = 1; i <= n; i++) {
                Stack<Integer> st = new Stack<Integer>();
                int con = 0;
                if (!isVisited[i]) {
                    st.push(i);
                }
                while (!st.isEmpty()) {
                    int item = st.pop();
                    isVisited[item] = true;
                    int j = map.get(item);
                    if (!isVisited[j]) {
                        st.push(j);
                    }
                    con++;
                }
                if (con != 0) {
                    if (con % 2 == 0) {
                        ans = lcm(ans, con / 2);
                    } else {
                        ans = lcm(ans, con);
                    }
                }
            }
            System.out.println(ans);
        }
    }

    static int lcm(int a, int b) {
        return a * b / gcd(a, b);
    }

    static int gcd(int a, int b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
}

class FastScanner {

    BufferedReader br;
    StringTokenizer tokenizer;

    FastScanner(String fileName) throws FileNotFoundException {
        this(new FileInputStream(new File(fileName)));
    }

    FastScanner(InputStream is) {
        br = new BufferedReader(new InputStreamReader(is));
    }

    String nextLine() throws IOException {
        tokenizer = null;
        return br.readLine();
    }

    String next() throws IOException {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            String line = br.readLine();
            if (line == null) {
                return null;
            }
            tokenizer = new StringTokenizer(line);
        }
        return tokenizer.nextToken();
    }

    int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    char nextChar() throws IOException {
        return next().charAt(0);
    }
}

// Main Code at the Bottom
import java.util.*;
import java.io.*;
public class Main{
	//Fast IO class
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
        	boolean env=System.getProperty("ONLINE_JUDGE") != null;
        	if(!env) {
        		try {
					br=new BufferedReader(new FileReader("src\\input.txt"));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
        	}
        	else br = new BufferedReader(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    static long MOD=1000000000+7;
    //debug
    static void debug(Object... o) {
        System.out.println(Arrays.deepToString(o));
    }
    // Pair
    static class pair{
    	long x,y;
    	pair(long a,long b){
    		this.x=a;
    		this.y=b;
    	}
    	public boolean equals(Object obj) {
    		if(obj == null || obj.getClass()!= this.getClass()) return false;
            pair p = (pair) obj;
            return (this.x==p.x && this.y==p.y);
        }
    	public int hashCode() {
            return Objects.hash(x,y);
        }
    }
    static FastReader sc=new FastReader();
    static PrintWriter out=new PrintWriter(System.out);
    //Global variables and functions
    static int gcd(int a,int b) {
    	return b==0?a:gcd(b,a%b);
    }
    static int lcm(int a,int b) {
    	return (a*b)/(gcd(a,b));
    }
    //Main function(The main code starts from here)
    public static void main (String[] args) throws java.lang.Exception {
    	int test=1;
    	//test=sc.nextInt();
    	while(test-->0) {
    		int n=sc.nextInt();
    		int a[]=new int[n];
    		for(int i=0;i<n;i++) a[i]=sc.nextInt()-1;
    		int visited[]=new int[n];
    		int ans=1;
    		for(int i=0;i<n;i++) {
    			if(visited[i]==1) continue;
    			int cnt=0,cur=i;
    			while(visited[cur]==0) {
    				visited[cur]=1;
    				cnt++;
    				cur=a[cur];
    			}
    			if(cur!=i) {
    				ans=-1;
    				break;
    			}
    			if(cnt%2==0) ans=lcm(ans,cnt/2);
    			else ans=lcm(ans,cnt);
    		}
    		out.println(ans);
    	}
        out.flush();
        out.close();
    }
}

/*

        HARSH KHATRI
        DA-IICT

                      */

import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class CF741A {

    static ArrayList<ArrayList<Integer>> makeDir(int v, int[] a) {

        ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
        for(int i =0; i<v; i++) {
            adj.add(new ArrayList<Integer>());
        }

        FasterScanner in = new FasterScanner();

        for(int i=0; i<v; i++) {
            (adj.get(i)).add(a[i]-1);
        }

        return adj;
    }

    static FasterScanner in = new FasterScanner();
    static int n = in.nextInt(), i, j, k;
    static boolean[] vis = new boolean[n];
    static boolean[] isCrush = new boolean[n];
    static int[] a = new int[n];

    static int dfs(ArrayList<ArrayList<Integer>> adj, int i, int count) {
        if(!vis[i]) {
            vis[i] = true;
            count++;
            for(int node : adj.get(i)) {
                return dfs(adj, node, count);
            }
        }
        return count;
    }

    static int GCD(int a, int b) {
        a = Math.abs(a);
        b = Math.abs(b);
        if(a==0) return b;
        else if(b==0) return a;
        else if(a==0 && b==0) return 0;
        else return GCD(b, (a%b) );
    }

    public static void main(String[] args) {

        int i, count;

        int same = 0;
        for(i = 0; i<n; i++) {
            a[i] = in.nextInt();
            isCrush[a[i]-1] = true;
        }

        boolean stop = false;
        for(i=0; i<n; i++) {
            if(!isCrush[i]) {
                System.out.println(-1);
                stop = true;
                break;
            }
        }

        if(!stop) {
            ArrayList<ArrayList<Integer>> adj = makeDir(n, a);

            int lcm = 1;

            for(i=0; i<n; i++) {
                if(!vis[i]) {
                    count = dfs(adj, i, 0);
                    if((count&1)==0) count >>= 1;
                    lcm = (lcm*count)/(GCD(lcm, count));
                }
            }

            System.out.println(lcm);
        }
    }
}

class FasterScanner {
        private byte[] buf = new byte[1024];
        private int curChar;
        private int snumChars;

        public int read() {
          if (snumChars == -1)
        throw new InputMismatchException();
          if (curChar >= snumChars) {
        curChar = 0;
        try {
          snumChars = System.in.read(buf);
        } catch (IOException e) {
          throw new InputMismatchException();
        }
        if (snumChars <= 0)
          return -1;
          }
          return buf[curChar++];
        }

        public double nextDouble() {
          return Double.parseDouble(this.nextString());
        }

        public String nextLine() {
          int c = read();
          while (isSpaceChar(c))
        c = read();
          StringBuilder res = new StringBuilder();
          do {
        res.appendCodePoint(c);
        c = read();
          } while (!isEndOfLine(c));
          return res.toString();
        }

        public String nextString() {
          int c = read();
          while (isSpaceChar(c))
        c = read();
          StringBuilder res = new StringBuilder();
          do {
        res.appendCodePoint(c);
        c = read();
          } while (!isSpaceChar(c));
          return res.toString();
        }

        public long nextLong() {
          int c = read();
          while (isSpaceChar(c))
        c = read();
          int sgn = 1;
          if (c == '-') {
        sgn = -1;
        c = read();
          }
          long res = 0;
          do {
        if (c < '0' || c > '9')
          throw new InputMismatchException();
        res *= 10;
        res += c - '0';
        c = read();
          } while (!isSpaceChar(c));
          return res * sgn;
        }

        public int nextInt() {
          int c = read();
          while (isSpaceChar(c))
        c = read();
          int sgn = 1;
          if (c == '-') {
        sgn = -1;
        c = read();
          }
          int res = 0;
          do {
        if (c < '0' || c > '9')
          throw new InputMismatchException();
        res *= 10;
        res += c - '0';
        c = read();
          } while (!isSpaceChar(c));
          return res * sgn;
        }

        public int[] nextIntArray(int n) {
          int[] arr = new int[n];
          for (int i = 0; i < n; i++) {
        arr[i] = nextInt();
          }
          return arr;
        }

        public long[] nextLongArray(int n) {
          long[] arr = new long[n];
          for (int i = 0; i < n; i++) {
        arr[i] = nextLong();
          }
          return arr;
        }

        private boolean isSpaceChar(int c) {
          return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
          return c == '\n' || c == '\r' || c == -1;
        }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Random;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Rustam Musin (PloadyFree@gmail.com)
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        private int n;
        private int[] call;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            n = in.readInt();
            call = IOUtils.readIntArray(in, n);
            MiscUtils.decreaseByOne(call);
            out.print(solve());
        }

        private long solve() {
            if (new IntHashSet(call).size() != n) {
                return -1;
            }

            long ans = 1;
            for (int i = 0; i < n; i++) {
                long len = findLen(i);
                if (len == -1) {
                    return -1;
                }
                ans = lcm(ans, len);
            }
            return ans;
        }

        private long lcm(long a, long b) {
            return (a / gcd(a, b)) * b;
        }

        private long gcd(long a, long b) {
            return b == 0 ? a : gcd(b, a % b);
        }

        private int findLen(int v) {
            boolean[] vis = new boolean[n];
            int v1 = v;
            int len = 1;
            while (true) {
                vis[v1] = true;
                v1 = call[v1];
                if (vis[v1]) {
                    break;
                }
                len++;
            }
            if (len == 1) {
                return 1;
            }
            if (len % 2 == 1) {
                return len;
            }
            return len / 2;
        }

    }

    static class IntArray extends IntAbstractStream implements IntList {
        private int[] data;

        public IntArray(int[] arr) {
            data = arr;
        }

        public int size() {
            return data.length;
        }

        public int get(int at) {
            return data[at];
        }

        public void addAt(int index, int value) {
            throw new UnsupportedOperationException();
        }

        public void removeAt(int index) {
            throw new UnsupportedOperationException();
        }

    }

    static abstract class IntAbstractStream implements IntStream {

        public String toString() {
            StringBuilder builder = new StringBuilder();
            boolean first = true;
            for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
                if (first) {
                    first = false;
                } else {
                    builder.append(' ');
                }
                builder.append(it.value());
            }
            return builder.toString();
        }

        public boolean equals(Object o) {
            if (!(o instanceof IntStream)) {
                return false;
            }
            IntStream c = (IntStream) o;
            IntIterator it = intIterator();
            IntIterator jt = c.intIterator();
            while (it.isValid() && jt.isValid()) {
                if (it.value() != jt.value()) {
                    return false;
                }
                it.advance();
                jt.advance();
            }
            return !it.isValid() && !jt.isValid();
        }

        public int hashCode() {
            int result = 0;
            for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
                result *= 31;
                result += it.value();
            }
            return result;
        }

    }

    static interface IntReversableCollection extends IntCollection {
    }

    static class MiscUtils {
        public static void decreaseByOne(int[]... arrays) {
            for (int[] array : arrays) {
                for (int i = 0; i < array.length; i++) {
                    array[i]--;
                }
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static interface IntIterator {
        public int value() throws NoSuchElementException;

        public boolean advance();

        public boolean isValid();

    }

    static class IntHashSet extends IntAbstractStream implements IntSet {
        private static final Random RND = new Random();
        private static final int[] SHIFTS = new int[4];
        private static final byte PRESENT_MASK = 1;
        private static final byte REMOVED_MASK = 2;
        private int size;
        private int realSize;
        private int[] values;
        private byte[] present;
        private int step;
        private int ratio;

        static {
            for (int i = 0; i < 4; i++) {
                SHIFTS[i] = RND.nextInt(31) + 1;
            }
        }

        public IntHashSet() {
            this(3);
        }

        public IntHashSet(int capacity) {
            capacity = Math.max(capacity, 3);
            values = new int[capacity];
            present = new byte[capacity];
            ratio = 2;
            initStep(capacity);
        }

        public IntHashSet(IntCollection c) {
            this(c.size());
            addAll(c);
        }

        public IntHashSet(int[] arr) {
            this(new IntArray(arr));
        }

        private void initStep(int capacity) {
            step = RND.nextInt(capacity - 2) + 1;
            while (IntegerUtils.gcd(step, capacity) != 1) {
                step++;
            }
        }

        public IntIterator intIterator() {
            return new IntIterator() {
                private int position = size == 0 ? values.length : -1;

                public int value() throws NoSuchElementException {
                    if (position == -1) {
                        advance();
                    }
                    if (position >= values.length) {
                        throw new NoSuchElementException();
                    }
                    if ((present[position] & PRESENT_MASK) == 0) {
                        throw new IllegalStateException();
                    }
                    return values[position];
                }

                public boolean advance() throws NoSuchElementException {
                    if (position >= values.length) {
                        throw new NoSuchElementException();
                    }
                    position++;
                    while (position < values.length && (present[position] & PRESENT_MASK) == 0) {
                        position++;
                    }
                    return isValid();
                }

                public boolean isValid() {
                    return position < values.length;
                }

                public void remove() {
                    if ((present[position] & PRESENT_MASK) == 0) {
                        throw new IllegalStateException();
                    }
                    present[position] = REMOVED_MASK;
                }
            };
        }

        public int size() {
            return size;
        }

        public void add(int value) {
            ensureCapacity((realSize + 1) * ratio + 2);
            int current = getHash(value);
            while (present[current] != 0) {
                if ((present[current] & PRESENT_MASK) != 0 && values[current] == value) {
                    return;
                }
                current += step;
                if (current >= values.length) {
                    current -= values.length;
                }
            }
            while ((present[current] & PRESENT_MASK) != 0) {
                current += step;
                if (current >= values.length) {
                    current -= values.length;
                }
            }
            if (present[current] == 0) {
                realSize++;
            }
            present[current] = PRESENT_MASK;
            values[current] = value;
            size++;
        }

        private int getHash(int value) {
            int hash = IntHash.hash(value);
            int result = hash;
            for (int i : SHIFTS) {
                result ^= hash >> i;
            }
            result %= values.length;
            if (result < 0) {
                result += values.length;
            }
            return result;
        }

        private void ensureCapacity(int capacity) {
            if (values.length < capacity) {
                capacity = Math.max(capacity * 2, values.length);
                rebuild(capacity);
            }
        }

        private void rebuild(int capacity) {
            initStep(capacity);
            int[] oldValues = values;
            byte[] oldPresent = present;
            values = new int[capacity];
            present = new byte[capacity];
            size = 0;
            realSize = 0;
            for (int i = 0; i < oldValues.length; i++) {
                if ((oldPresent[i] & PRESENT_MASK) == PRESENT_MASK) {
                    add(oldValues[i]);
                }
            }
        }

    }

    static class IOUtils {
        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.readInt();
            }
            return array;
        }

    }

    static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
        public IntIterator intIterator();

        default public Iterator<Integer> iterator() {
            return new Iterator<Integer>() {
                private IntIterator it = intIterator();

                public boolean hasNext() {
                    return it.isValid();
                }

                public Integer next() {
                    int result = it.value();
                    it.advance();
                    return result;
                }
            };
        }

        default public int compareTo(IntStream c) {
            IntIterator it = intIterator();
            IntIterator jt = c.intIterator();
            while (it.isValid() && jt.isValid()) {
                int i = it.value();
                int j = jt.value();
                if (i < j) {
                    return -1;
                } else if (i > j) {
                    return 1;
                }
                it.advance();
                jt.advance();
            }
            if (it.isValid()) {
                return 1;
            }
            if (jt.isValid()) {
                return -1;
            }
            return 0;
        }

    }

    static class IntHash {
        private IntHash() {
        }

        public static int hash(int c) {
            return c;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void print(long i) {
            writer.print(i);
        }

    }

    static interface IntCollection extends IntStream {
        public int size();

        default public void add(int value) {
            throw new UnsupportedOperationException();
        }

        default public IntCollection addAll(IntStream values) {
            for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) {
                add(it.value());
            }
            return this;
        }

    }

    static class IntegerUtils {
        public static int gcd(int a, int b) {
            a = Math.abs(a);
            b = Math.abs(b);
            while (b != 0) {
                int temp = a % b;
                a = b;
                b = temp;
            }
            return a;
        }

    }

    static interface IntList extends IntReversableCollection {
        public abstract int get(int index);

        public abstract void addAt(int index, int value);

        public abstract void removeAt(int index);

        default public IntIterator intIterator() {
            return new IntIterator() {
                private int at;
                private boolean removed;

                public int value() {
                    if (removed) {
                        throw new IllegalStateException();
                    }
                    return get(at);
                }

                public boolean advance() {
                    at++;
                    removed = false;
                    return isValid();
                }

                public boolean isValid() {
                    return !removed && at < size();
                }

                public void remove() {
                    removeAt(at);
                    at--;
                    removed = true;
                }
            };
        }

        default public void add(int value) {
            addAt(size(), value);
        }

    }

    static interface IntSet extends IntCollection {
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int crushes[] = in.readIntArray(n);
            for (int i = 0; i < crushes.length; i++) {
                crushes[i] -= 1;
            }
            for (int t = 1; t <= n * n; t++) {
                boolean isPos = true;
                for (int i = 0; i < n; i++) {
                    int y = getEnd(i, t, crushes);
                    int x = getEnd(y, t, crushes);
                    if (x != i) {
                        isPos = false;
                        break;
                    }
                }
                if (isPos) {
                    out.println(t);
                    return;
                }
            }
            out.println(-1);
        }

        private int getEnd(int st, int t, int crushes[]) {
            if (t == 0) {
                return st;
            } else {
                return getEnd(crushes[st], t - 1, crushes);
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        private boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public int[] readIntArray(int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++)
                array[i] = readInt();
            return array;
        }

        public int nextInt() {
            return readInt();
        }

    }
}

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
        solver.solve(in, out);
        out.close();
    }
}

class Task {

    static int MAX = 1000001;
    int[] a;
    boolean[] used;

    public void solve(Scanner in, PrintWriter out) {
        int n = in.nextInt();
        a = new int[n];
        used = new boolean[n];
        Arrays.fill(used, false);
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt() - 1;
        }
        int result = -1;
        for (int i = 0; i < n; i++) {
            if (!used[i]) {
                int cycleSize = cycle(i, i);
//                System.out.println(cycleSize);
                if (cycleSize < 0) {
                    System.out.println(-1);
                    return;
                }
                if (cycleSize != 1) {
                    cycleSize = cycleSize % 2 == 0 ? cycleSize / 2 : cycleSize;
                    if (result == -1) {
                        result = cycleSize;
                    } else {
                        result = nod(cycleSize, result);
                    }
                }
            }
        }
        if (result == -1) {
            System.out.println(1);
            return;
        }
        System.out.println(result);
    }

    int nod(int a, int b) {
        return b != 0 ? nod(b, a % b) : a;
    }

    int cycle(int start, int curr) {
        if (a[curr] == start) {
            used[curr] = true;
            return 1;
        }
        if (used[curr]) {
            return -300;
        }
        used[curr] = true;
        return cycle(start, a[curr]) + 1;
    }

}

class Utils {

    public static int binarySearch(int[] a, int key) {
        int s = 0;
        int f = a.length;
        while (f > s) {
            int mid = (s + f) / 2;
            if (a[mid] > key) {
                f = mid;
            } else if (a[mid] <= key) {
                s = mid + 1;
            }
        }
        return -1;
    }
}

class Scanner {
    BufferedReader in;
    StringTokenizer tok;

    public Scanner(InputStream in) {
        this.in = new BufferedReader(new InputStreamReader(in));
        tok = new StringTokenizer("");
    }

    private String tryReadNextLine() {
        try {
            return in.readLine();
        } catch (Exception e) {
            throw new InputMismatchException();
        }
    }

    public String nextToken() {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(next());
        }
        return tok.nextToken();
    }

    public String next() {
        String newLine = tryReadNextLine();
        if (newLine == null)
            throw new InputMismatchException();
        return newLine;
    }

    public int nextInt() {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() {
        return Long.parseLong(nextToken());
    }
}

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
        solver.solve(in, out);
        out.close();
    }
}

class Task {

    static int MAX = 1000001;
    int[] a;
    boolean[] used;

    public void solve(Scanner in, PrintWriter out) {
        int n = in.nextInt();
        a = new int[n];
        used = new boolean[n];
        Arrays.fill(used, false);
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt() - 1;
        }
        int result = 200;
        for (int i = 0; i < n; i++) {
            if (!used[i]) {
                int cycleSize = cycle(i, i);
//                System.out.println(cycleSize);
                if (cycleSize < 0) {
                    System.out.println(-1);
                    return;
                }
                if (cycleSize != 1) {
                    cycleSize = cycleSize % 2 == 0 ? cycleSize / 2 : cycleSize;
                    if (cycleSize < result) {
                        result = cycleSize;
                    }
                }
            }
        }
        if (result == 200) {
            System.out.println(1);
            return;
        }
        System.out.println(result);
    }

    int cycle(int start, int curr) {
        if (a[curr] == start) {
            used[curr] = true;
            return 1;
        }
        if (used[curr]) {
            return -300;
        }
        used[curr] = true;
        return cycle(start, a[curr]) + 1;
    }

}

class Utils {

    public static int binarySearch(int[] a, int key) {
        int s = 0;
        int f = a.length;
        while (f > s) {
            int mid = (s + f) / 2;
            if (a[mid] > key) {
                f = mid;
            } else if (a[mid] <= key) {
                s = mid + 1;
            }
        }
        return -1;
    }
}

class Scanner {
    BufferedReader in;
    StringTokenizer tok;

    public Scanner(InputStream in) {
        this.in = new BufferedReader(new InputStreamReader(in));
        tok = new StringTokenizer("");
    }

    private String tryReadNextLine() {
        try {
            return in.readLine();
        } catch (Exception e) {
            throw new InputMismatchException();
        }
    }

    public String nextToken() {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(next());
        }
        return tok.nextToken();
    }

    public String next() {
        String newLine = tryReadNextLine();
        if (newLine == null)
            throw new InputMismatchException();
        return newLine;
    }

    public int nextInt() {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() {
        return Long.parseLong(nextToken());
    }
}

/*
 * Remember a 6.0 student can know more than a 10.0 student.
 * Grades don't determine intelligence, they test obedience.
 * I Never Give Up.
 * I will become Candidate Master.
 * I will defeat Saurabh Anand.
 * Skills are Cheap,Passion is Priceless.
 */
import java.util.*;
import java.util.Map.Entry;
import java.io.*;

import static java.lang.System.out;
import static java.util.Arrays.*;
import static java.lang.Math.*;

public class ContestMain{
	private static Reader in=new Reader();
	private static StringBuilder ans=new StringBuilder();
	private static long MOD=1000000000+7;// 1e9+7
	private static final int N=200000+7; // 2e5+7
//    private static final double EPS=1e-9;
//    private static final int LIM=26;
//    private static final double PI=3.1415;
//    private static ArrayList<Integer> v[]=new ArrayList[N];
//    private static int color[]=new int[N];
	private static boolean mark[]=new boolean[N];

//    private static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//    private static ArrayList<Pair> v[]=new ArrayList[N];
	private static long powmod(long x,long n){
		if(n==0||x==0)
			return 1;
		else if(n%2==0)
			return(powmod((x*x)%MOD,n/2));
		else
			return (x*(powmod((x*x)%MOD,(n-1)/2)))%MOD;
	}

	private static void shuffle(long[] arr){
		for(int i=arr.length-1;i>=2;i--){
			int x=new Random().nextInt(i-1);
			long temp=arr[x];
			arr[x]=arr[i];
			arr[i]=temp;
		}
	}

//    private static long gcd(long a, long b){
//        if(b==0)return a;
//        return gcd(b,a%b);
//    }
//    private static boolean check(int x,int y){
//        if((x>=0&&x<n)&&(y>=0&&y<m)&&mat[x][y]!='X'&&!visited[x][y])return true;
//        return false;
//    }
	public static void main(String[] args) throws IOException{
		int n=in.nextInt();
		int ar[]=new int[n+1];
		for(int i=1;i<=n;i++)
			ar[i]=in.nextInt();
		int node=0,res=0;
		HashSet<Integer> set=new HashSet();
		HashSet<Integer> resSet=new HashSet();
		boolean flag;
		for(int i=1;i<=n;i++){
			node=i;
			flag=false;
			while(true){
				if(set.contains(node)){
					if(node==i)flag=true;
					else flag=false;
					break;
				}
				set.add(node);
				node=ar[node];
			}
			resSet.add(set.size());
			set.clear();
			if(!flag||resSet.size()>2){out.println(-1);return;}
		}
		if(resSet.size()==2&&!resSet.contains(1)){out.println(-1);return;}
		for(int a:resSet){
			if(a!=1){
				if(a==2)out.println(1);
				else out.println(a);
				return;
			}
		}
		out.println(-1);
	}
	static class Pair<T> implements Comparable<Pair>{
		long l;
		long r;

		Pair(){
			l=0;
			r=0;
		}

		Pair(long k,long v){
			l=k;
			r=v;
		}

		@Override
		public int compareTo(Pair o){
			if(o.l!=l)
				return (int)-(l-o.l);
			else
				return (int)(r-o.r);
		}
		// Fenwick tree question comparator
//        @Override
//        public int compareTo(Pair o) {
//            if(o.r!=r)return (int) (r-o.r);
//            else return (int)(l-o.l);
//        }
	}

	static class Reader{
		BufferedReader br;
		StringTokenizer st;

		public Reader(){
			br=new BufferedReader(new InputStreamReader(System.in));
		}

		String next(){
			while(st==null||!st.hasMoreElements()){
				try{

					st=new StringTokenizer(br.readLine());
				}catch(IOException e){
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt(){
			return Integer.parseInt(next());
		}

		long nextLong(){
			return Long.parseLong(next());
		}

		double nextDouble(){
			return Double.parseDouble(next());
		}

		String nextLine(){
			String str="";
			try{
				str=br.readLine();
			}catch(IOException e){
				e.printStackTrace();
			}
			return str;
		}
	}
}

import java.util.Scanner;

import java.util.Arrays;

public class Main {
  static final int INF = Integer.MAX_VALUE / 2;
  static int n;
  static int[] c;

  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);

    n = sc.nextInt();
    c = new int[n];
    for(int i = 0; i < n; i++){
      c[i] = sc.nextInt() - 1;
    }
    int[] deg = new int[n];
    Arrays.fill(deg, 1);
    for(int i = 0; i < n; i++){
      deg[c[i]]++;
    }

    int t = INF;
    for(int s = 0; s < n; s++){
      if(deg[s] <= 1){
        continue;
      }
      int v = s, d = 0, w = -1;
      do{
        w = v;
        v = c[v];
        ++d;
      }while(v != w && v != s);
      if(v == s && d > 1){
        if(d == 2){
          t = Math.min(t, 1);
        }
        else{
          t = Math.min(t, d);
        }
      }
    }

    if(t != INF){
      System.out.println(t);
    }
    else{
      System.out.println(-1);
    }
  }
}

//package baobab;

import java.io.*;
import java.util.*;

public class C {

    public static void main(String[] args) {
        Solver solver = new Solver();
    }

    static class Solver {
        IO io;

        public Solver() {
            this.io = new IO();
            try {
                solve();
            } finally {
                io.close();
            }
        }

        /****************************** START READING HERE ********************************/

        void solve() {
            int n = io.nextInt();
            int[] crush = new int[n+1];
            for (int i=1; i<=n; i++) {
                crush[i] = io.nextInt();
            }
            boolean[] impossible = new boolean[n+1];
            for (int start=1; start<=n; start++) {
                int t = 0;
                int curr = start;
                boolean[] vis = new boolean[n+1];
                while (!vis[curr]) {
                    vis[curr] = true;
                    curr = crush[curr];
                    t++;
                }
                if (curr != start) {
                    io.println(-1);
                    return;
                }
                if (t%2 == 0) {
                    t /= 2;
                }
                int possible = t;
                for (t=1; t<=n; t++) {
                    if (t % possible != 0) impossible[t] = true;
                }
            }

            for (int t=1; t<=n; t++) {
                if (impossible[t]) continue;
                io.println(t);
                return;
            }

            io.println(-1);
        }

        /************************** UTILITY CODE BELOW THIS LINE **************************/

        long MOD = (long)1e9 + 7;

        List<Integer>[] toGraph(IO io, int n) {
            List<Integer>[] g = new ArrayList[n+1];
            for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
            for (int i=1; i<=n-1; i++) {
                int a = io.nextInt();
                int b = io.nextInt();
                g[a].add(b);
                g[b].add(a);
            }
            return g;
        }

        class Point {
            int y;
            int x;

            public Point(int y, int x) {
                this.y = y;
                this.x = x;
            }
        }

        class IDval implements Comparable<IDval> {
            int id;
            long val;

            public IDval(int id, long val) {
                this.val = val;
                this.id = id;
            }

            @Override
            public int compareTo(IDval o) {
                if (this.val < o.val) return -1;
                if (this.val > o.val) return 1;
                return this.id - o.id;
            }
        }

        long pow(long base, int exp) {
            if (exp == 0) return 1L;
            long x = pow(base, exp/2);
            long ans = x * x;
            if (exp % 2 != 0) ans *= base;
            return ans;
        }

        class ElementCounter {
            private HashMap<Long, Long> elements;

            public ElementCounter() {
                elements = new HashMap<>();
            }

            public void add(long element) {
                long count = 1;
                if (elements.containsKey(element)) count += elements.get(element);
                elements.put(element, count);
            }

            public void remove(long element) {
                long count = elements.get(element);
                count--;
                if (count == 0) elements.remove(element);
                else elements.put(element, count);
            }

            public long get(long element) {
                if (!elements.containsKey(element)) return 0;
                return elements.get(element);
            }

            public int size() {
                return elements.size();
            }
        }

        class StringCounter {
            HashMap<String, Long> elements;

            public StringCounter() {
                elements = new HashMap<>();
            }

            public void add(String identifier) {
                long count = 1;
                if (elements.containsKey(identifier)) count += elements.get(identifier);
                elements.put(identifier, count);
            }

            public void remove(String identifier) {
                long count = elements.get(identifier);
                count--;
                if (count == 0) elements.remove(identifier);
                else elements.put(identifier, count);
            }

            public long get(String identifier) {
                if (!elements.containsKey(identifier)) return 0;
                return elements.get(identifier);
            }

            public int size() {
                return elements.size();
            }
        }

        class LCAFinder {

            /* O(n log n) Initialize: new LCAFinder(graph)
             * O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */

            int[] nodes;
            int[] depths;
            int[] entries;
            int pointer;
            FenwickMin fenwick;

            public LCAFinder(List<Integer>[] graph) {
                this.nodes = new int[(int)10e6];
                this.depths = new int[(int)10e6];
                this.entries = new int[graph.length];
                this.pointer = 1;
                boolean[] visited = new boolean[graph.length+1];
                dfs(1, 0, graph, visited);
                fenwick = new FenwickMin(pointer-1);
                for (int i=1; i<pointer; i++) {
                    fenwick.set(i, depths[i] * 1000000L + i);
                }
            }

            private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
                visited[node] = true;
                entries[node] = pointer;
                nodes[pointer] = node;
                depths[pointer] = depth;
                pointer++;
                for (int neighbor : graph[node]) {
                    if (visited[neighbor]) continue;
                    dfs(neighbor, depth+1, graph, visited);
                    nodes[pointer] = node;
                    depths[pointer] = depth;
                    pointer++;
                }
            }

            public int find(int a, int b) {
                int left = entries[a];
                int right = entries[b];
                if (left > right) {
                    int temp = left;
                    left = right;
                    right = temp;
                }
                long mixedBag = fenwick.getMin(left, right);
                int index = (int) (mixedBag % 1000000L);
                return nodes[index];
            }
        }

        class FenwickMin {
            long n;
            long[] original;
            long[] bottomUp;
            long[] topDown;

            public FenwickMin(int n) {
                this.n = n;
                original = new long[n+2];
                bottomUp = new long[n+2];
                topDown = new long[n+2];
            }

            public void set(int modifiedNode, long value) {
                long replaced = original[modifiedNode];
                original[modifiedNode] = value;
                // Update left tree
                int i = modifiedNode;
                long v = value;
                while (i <= n) {
                    if (v > bottomUp[i]) {
                        if (replaced == bottomUp[i]) {
                            v = Math.min(v, original[i]);
                            for (int r=1 ;; r++) {
                                int x = (i&-i)>>>r;
                                if (x == 0) break;
                                int child = i-x;
                                v = Math.min(v, bottomUp[child]);
                            }
                        } else break;
                    }
                    if (v == bottomUp[i]) break;
                    bottomUp[i] = v;
                    i += (i&-i);
                }
                // Update right tree
                i = modifiedNode;
                v = value;
                while (i > 0) {
                    if (v > topDown[i]) {
                        if (replaced == topDown[i]) {
                            v = Math.min(v, original[i]);
                            for (int r=1 ;; r++) {
                                int x = (i&-i)>>>r;
                                if (x == 0) break;
                                int child = i+x;
                                if (child > n+1) break;
                                v = Math.min(v, topDown[child]);
                            }
                        } else break;
                    }
                    if (v == topDown[i]) break;
                    topDown[i] = v;
                    i -= (i&-i);
                }
            }

            public long getMin(int a, int b) {
                long min = original[a];
                int prev = a;
                int curr = prev + (prev&-prev); // parent right hand side
                while (curr <= b) {
                    min = Math.min(min, topDown[prev]); // value from the other tree
                    prev = curr;
                    curr = prev + (prev&-prev);;
                }
                min = Math.min(min, original[prev]);
                prev = b;
                curr = prev - (prev&-prev); // parent left hand side
                while (curr >= a) {
                    min = Math.min(min,bottomUp[prev]); // value from the other tree
                    prev = curr;
                    curr = prev - (prev&-prev);
                }
                return min;
            }

        }

        class FenwickSum {
            public long[] d;

            public FenwickSum(int n) {
                d=new long[n+1];
            }

            /** a[0] must be unused. */
            public FenwickSum(long[] a) {
                d=new long[a.length];
                for (int i=1; i<a.length; i++) {
                    modify(i, a[i]);
                }
            }

            /** Do not modify i=0. */
            void modify(int i, long v) {
                while (i<d.length) {
                    d[i] += v;
                    // Move to next uplink on the RIGHT side of i
                    i += (i&-i);
                }
            }

            /** Returns sum from a to b, *BOTH* inclusive. */
            long getSum(int a, int b) {
                return getSum(b) - getSum(a-1);
            }

            private long getSum(int i) {
                long sum = 0;
                while (i>0) {
                    sum += d[i];
                    // Move to next uplink on the LEFT side of i
                    i -= (i&-i);
                }
                return sum;
            }
        }

        class SegmentTree {
            /** Query sums with log(n) modifyRange */
            int N;
            long[] p;

            public SegmentTree(int n) {
                /* TODO: Test that this works. */
                N = n;
                p = new long[2*N];
            }

            public void modifyRange(int a, int b, long change) {
                muuta(a, change);
                muuta(b+1, -change);
            }

            void muuta(int k, long muutos) {
                k += N;
                p[k] += muutos;
                for (k /= 2; k >= 1; k /= 2) {
                    p[k] = p[2*k] + p[2*k+1];
                }
            }

            public long get(int k) {
                int a = N;
                int b = k+N;
                long s = 0;
                while (a <= b) {
                    if (a%2 == 1) s += p[a++];
                    if (b%2 == 0) s += p[b--];
                    a /= 2;
                    b /= 2;
                }
                return s;
            }

        }

        class Zalgo {

            public int pisinEsiintyma(String haku, String kohde) {
                char[] s = new char[haku.length() + 1 + kohde.length()];
                for (int i=0; i<haku.length(); i++) {
                    s[i] = haku.charAt(i);
                }
                int j = haku.length();
                s[j++] = '#';
                for (int i=0; i<kohde.length(); i++) {
                    s[j++] = kohde.charAt(i);
                }
                int[] z = toZarray(s);
                int max = 0;
                for (int i=haku.length(); i<z.length; i++) {
                    max = Math.max(max, z[i]);
                }
                return max;
            }

            public int[] toZarray(char[] s) {
                int n = s.length;
                int[] z = new int[n];
                int a = 0, b = 0;
                for (int i = 1; i < n; i++) {
                    if (i > b) {
                        for (int j = i; j < n && s[j - i] == s[j]; j++)  z[i]++;
                    }
                    else {
                        z[i] = z[i - a];
                        if (i + z[i - a] > b) {
                            for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
                            a = i;
                            b = i + z[i] - 1;
                        }
                    }
                }
                return z;
            }

            public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
                // this is alternative use case
                char[] s = new char[haku.length() + 1 + kohde.length()];
                for (int i=0; i<haku.length(); i++) {
                    s[i] = haku.charAt(i);
                }
                int j = haku.length();
                s[j++] = '#';
                for (int i=0; i<kohde.length(); i++) {
                    s[j++] = kohde.charAt(i);
                }
                int[] z = toZarray(s);
                List<Integer> indexes = new ArrayList<>();
                for (int i=haku.length(); i<z.length; i++) {
                    if (z[i] < haku.length()) continue;
                    indexes.add(i);
                }
                return indexes;
            }

        }

        class StringHasher {

            class HashedString {
                long[] hashes;
                long[] modifiers;

                public HashedString(long[] hashes, long[] modifiers) {
                    this.hashes = hashes;
                    this.modifiers = modifiers;
                }
            }

            long P;
            long M;

            public StringHasher() {
                initializePandM();
            }

            HashedString hashString(String s) {
                int n = s.length();
                long[] hashes = new long[n];
                long[] modifiers = new long[n];
                hashes[0] = s.charAt(0);
                modifiers[0] = 1;
                for (int i=1; i<n; i++) {
                    hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
                    modifiers[i] = (modifiers[i-1] * P) % M;
                }
                return new HashedString(hashes, modifiers);
            }

            /**
             * Indices are inclusive.
             */
            long getHash(HashedString hashedString, int startIndex, int endIndex) {
                long[] hashes = hashedString.hashes;
                long[] modifiers = hashedString.modifiers;
                long result = hashes[endIndex];
                if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
                if (result < 0) result += M;
                return result;
            }

            // Less interesting methods below

            /**
             * Efficient for 2 input parameter strings in particular.
             */
            HashedString[] hashString(String first, String second) {
                HashedString[] array = new HashedString[2];
                int n = first.length();
                long[] modifiers = new long[n];
                modifiers[0] = 1;

                long[] firstHashes = new long[n];
                firstHashes[0] = first.charAt(0);
                array[0] = new HashedString(firstHashes, modifiers);

                long[] secondHashes = new long[n];
                secondHashes[0] = second.charAt(0);
                array[1] = new HashedString(secondHashes, modifiers);

                for (int i=1; i<n; i++) {
                    modifiers[i] = (modifiers[i-1] * P) % M;
                    firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
                    secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
                }
                return array;
            }

            /**
             * Efficient for 3+ strings
             * More efficient than multiple hashString calls IF strings are same length.
             */
            HashedString[] hashString(String... strings) {
                HashedString[] array = new HashedString[strings.length];
                int n = strings[0].length();
                long[] modifiers = new long[n];
                modifiers[0] = 1;
                for (int j=0; j<strings.length; j++) {
                    // if all strings are not same length, defer work to another method
                    if (strings[j].length() != n) {
                        for (int i=0; i<n; i++) {
                            array[i] = hashString(strings[i]);
                        }
                        return array;
                    }

                    // otherwise initialize stuff
                    long[] hashes = new long[n];
                    hashes[0] = strings[j].charAt(0);
                    array[j] = new HashedString(hashes, modifiers);
                }
                for (int i=1; i<n; i++) {
                    modifiers[i] = (modifiers[i-1] * P) % M;
                    for (int j=0; j<strings.length; j++) {
                        String s = strings[j];
                        long[] hashes = array[j].hashes;
                        hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
                    }
                }
                return array;
            }

            void initializePandM() {
                ArrayList<Long> modOptions = new ArrayList<>(20);
                modOptions.add(353873237L);
                modOptions.add(353875897L);
                modOptions.add(353878703L);
                modOptions.add(353882671L);
                modOptions.add(353885303L);
                modOptions.add(353888377L);
                modOptions.add(353893457L);
                P = modOptions.get(new Random().nextInt(modOptions.size()));

                modOptions.clear();
                modOptions.add(452940277L);
                modOptions.add(452947687L);
                modOptions.add(464478431L);
                modOptions.add(468098221L);
                modOptions.add(470374601L);
                modOptions.add(472879717L);
                modOptions.add(472881973L);
                M = modOptions.get(new Random().nextInt(modOptions.size()));

            }
        }

        private static class Prob {

            /** For heavy calculations on probabilities, this class
             *  provides more accuracy & efficiency than doubles.
             *  Math explained: https://en.wikipedia.org/wiki/Log_probability
             *  Quick start:
             *      - Instantiate probabilities, eg. Prob a = new Prob(0.75)
             *      - add(), multiply() return new objects, can perform on nulls & NaNs.
             *      - get() returns probability as a readable double */

            /** Logarithmized probability. Note: 0% represented by logP NaN. */
            private double logP;

            /** Construct instance with real probability. */
            public Prob(double real) {
                if (real > 0) this.logP = Math.log(real);
                else this.logP = Double.NaN;
            }

            /** Construct instance with already logarithmized value. */
            static boolean dontLogAgain = true;
            public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
                this.logP = logP;
            }

            /** Returns real probability as a double. */
            public double get() {
                return Math.exp(logP);
            }

            @Override
            public String toString() {
                return ""+get();
            }

            /***************** STATIC METHODS BELOW ********************/

            /** Note: returns NaN only when a && b are both NaN/null. */
            public static Prob add(Prob a, Prob b) {
                if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
                if (nullOrNaN(a)) return copy(b);
                if (nullOrNaN(b)) return copy(a);

                double x = a.logP;
                double y = b.logP;
                double sum = x + Math.log(1 + Math.exp(y - x));
                return new Prob(sum, dontLogAgain);
            }

            /** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
            public static Prob multiply(Prob a, Prob b) {
                if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
                return new Prob(a.logP + b.logP, dontLogAgain);
            }

            /** Returns true if p is null or NaN. */
            private static boolean nullOrNaN(Prob p) {
                return (p == null || Double.isNaN(p.logP));
            }

            /** Returns a new instance with the same value as original. */
            private static Prob copy(Prob original) {
                return new Prob(original.logP, dontLogAgain);
            }
        }

        public class StronglyConnectedComponents {

            /** Kosaraju's algorithm */

            ArrayList<Integer>[] forw;
            ArrayList<Integer>[] bacw;

            /** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */
            public int getCount(int n, int[] mista, int[] minne) {
                forw = new ArrayList[n+1];
                bacw = new ArrayList[n+1];
                for (int i=1; i<=n; i++) {
                    forw[i] = new ArrayList<Integer>();
                    bacw[i] = new ArrayList<Integer>();
                }
                for (int i=0; i<mista.length; i++) {
                    int a = mista[i];
                    int b = minne[i];
                    forw[a].add(b);
                    bacw[b].add(a);
                }
                int count = 0;
                List<Integer> list = new ArrayList<Integer>();
                boolean[] visited = new boolean[n+1];
                for (int i=1; i<=n; i++) {
                    dfsForward(i, visited, list);
                }
                visited = new boolean[n+1];
                for (int i=n-1; i>=0; i--) {
                    int node = list.get(i);
                    if (visited[node]) continue;
                    count++;
                    dfsBackward(node, visited);
                }
                return count;
            }

            public void dfsForward(int i, boolean[] visited, List<Integer> list) {
                if (visited[i]) return;
                visited[i] = true;
                for (int neighbor : forw[i]) {
                    dfsForward(neighbor, visited, list);
                }
                list.add(i);
            }

            public void dfsBackward(int i, boolean[] visited) {
                if (visited[i]) return;
                visited[i] = true;
                for (int neighbor : bacw[i]) {
                    dfsBackward(neighbor, visited);
                }
            }
        }

        class DrawGrid {

            void draw(boolean[][] d) {
                System.out.print("  ");
                for (int x=0; x<d[0].length; x++) {
                    System.out.print(" " + x + " ");
                }
                System.out.println("");
                for (int y=0; y<d.length; y++) {
                    System.out.print(y + " ");
                    for (int x=0; x<d[0].length; x++) {
                        System.out.print((d[y][x] ? "[x]" : "[ ]"));
                    }
                    System.out.println("");
                }
            }

            void draw(int[][] d) {
                int max = 1;
                for (int y=0; y<d.length; y++) {
                    for (int x=0; x<d[0].length; x++) {
                        max = Math.max(max, ("" + d[y][x]).length());
                    }
                }
                System.out.print("  ");
                String format = "%" + (max+2) + "s";
                for (int x=0; x<d[0].length; x++) {
                    System.out.print(String.format(format, x) + " ");
                }
                format = "%" + (max) + "s";
                System.out.println("");
                for (int y=0; y<d.length; y++) {
                    System.out.print(y + " ");
                    for (int x=0; x<d[0].length; x++) {
                        System.out.print(" [" + String.format(format, (d[y][x])) + "]");
                    }
                    System.out.println("");
                }
            }

        }

        class BaseConverter {

            /* Palauttaa luvun esityksen kannassa base */
            public String convert(Long number, int base) {
                return Long.toString(number, base);
            }

            /* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */
            public String convert(String number, int baseFrom, int baseTo) {
                return Long.toString(Long.parseLong(number, baseFrom), baseTo);
            }

            /* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
            public long longify(String number, int baseFrom) {
                return Long.parseLong(number, baseFrom);
            }
        }

        class Binary implements Comparable<Binary> {

            /**
             * Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
             *
             * When manipulating small binary strings, instantiate new Binary(string)
             * When just reading large binary strings, instantiate new Binary(string,true)
             * get(int i) returns a character '1' or '0', not an int.
             */

            private boolean[] d;
            private int first; // Starting from left, the first (most remarkable) '1'
            public int length;

            public Binary(String binaryString) {
                this(binaryString, false);
            }
            public Binary(String binaryString, boolean initWithMinArraySize) {
                length = binaryString.length();
                int size = Math.max(2*length, 1);
                first = length/4;
                if (initWithMinArraySize) {
                    first = 0;
                    size = Math.max(length, 1);
                }
                d = new boolean[size];
                for (int i=0; i<length; i++) {
                    if (binaryString.charAt(i) == '1') d[i+first] = true;
                }
            }

            public void addFirst(char c) {
                if (first-1 < 0) doubleArraySize();
                first--;
                d[first] = (c == '1' ? true : false);
                length++;
            }

            public void addLast(char c) {
                if (first+length >= d.length) doubleArraySize();
                d[first+length] = (c == '1' ? true : false);
                length++;
            }

            private void doubleArraySize() {
                boolean[] bigArray = new boolean[(d.length+1) * 2];
                int newFirst = bigArray.length / 4;
                for (int i=0; i<length; i++) {
                    bigArray[i + newFirst] = d[i + first];
                }
                first = newFirst;
                d = bigArray;
            }

            public boolean flip(int i) {
                boolean value = (this.d[first+i] ? false : true);
                this.d[first+i] = value;
                return value;
            }

            public void set(int i, char c) {
                boolean value = (c == '1' ? true : false);
                this.d[first+i] = value;
            }

            public char get(int i) {
                return (this.d[first+i] ? '1' : '0');
            }

            @Override
            public int compareTo(Binary o) {
                if (this.length != o.length) return this.length - o.length;
                int len = this.length;
                for (int i=0; i<len; i++) {
                    int diff = this.get(i) - o.get(i);
                    if (diff != 0) return diff;
                }
                return 0;
            }

            @Override
            public String toString() {
                StringBuilder sb = new StringBuilder();
                for (int i=0; i<length; i++) {
                    sb.append(d[i+first] ? '1' : '0');
                }
                return sb.toString();
            }

        }

        class BinomialCoefficients {
            /** Total number of K sized unique combinations from pool of size N (unordered)
             N! / ( K! (N - K)! )   */

            /** For simple queries where output fits in long. */
            public long biCo(long n, long k) {
                long r = 1;
                if (k > n) return 0;
                for (long d = 1; d <= k; d++) {
                    r *= n--;
                    r /= d;
                }
                return r;
            }

            /** For multiple queries with same n, different k. */
            public long[] precalcBinomialCoefficientsK(int n, int maxK) {
                long v[] = new long[maxK+1];
                v[0] = 1; // nC0 == 1
                for (int i=1; i<=n; i++) {
                    for (int j=Math.min(i,maxK); j>0; j--) {
                        v[j] = v[j] + v[j-1]; // Pascal's triangle
                    }
                }
                return v;
            }

            /** When output needs % MOD. */
            public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
                long v[] = new long[k+1];
                v[0] = 1; // nC0 == 1
                for (int i=1; i<=n; i++) {
                    for (int j=Math.min(i,k); j>0; j--) {
                        v[j] = v[j] + v[j-1]; // Pascal's triangle
                        v[j] %= M;
                    }
                }
                return v;
            }
        }

        class GreatestCommonDivisor {

            /** Chained calls to Euclidean algorithm. */
            long gcd(long... v) {
                if (v.length == 1) return v[0];
                long ans = gcd(v[1], v[0]);
                for (int i=2; i<v.length; i++) {
                    ans = gcd(ans, v[i]);
                }
                return ans;
            }

            /** Euclidean algorithm. */
            long gcd(long a, long b) {
                if (b == 0) return a;
                return gcd(b, a%b);
            }
        }

        private class IO extends PrintWriter {
            private InputStreamReader r;
            private static final int BUFSIZE = 1 << 15;
            private char[] buf;
            private int bufc;
            private int bufi;
            private StringBuilder sb;

            public IO() {
                super(new BufferedOutputStream(System.out));
                r = new InputStreamReader(System.in);

                buf = new char[BUFSIZE];
                bufc = 0;
                bufi = 0;
                sb = new StringBuilder();
            }

            private void fillBuf() throws IOException {
                bufi = 0;
                bufc = 0;
                while(bufc == 0) {
                    bufc = r.read(buf, 0, BUFSIZE);
                    if(bufc == -1) {
                        bufc = 0;
                        return;
                    }
                }
            }

            private boolean pumpBuf() throws IOException {
                if(bufi == bufc) {
                    fillBuf();
                }
                return bufc != 0;
            }

            private boolean isDelimiter(char c) {
                return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
            }

            private void eatDelimiters() throws IOException {
                while(true) {
                    if(bufi == bufc) {
                        fillBuf();
                        if(bufc == 0) throw new RuntimeException("IO: Out of input.");
                    }

                    if(!isDelimiter(buf[bufi])) break;
                    ++bufi;
                }
            }

            public String next() {
                try {
                    sb.setLength(0);

                    eatDelimiters();
                    int start = bufi;

                    while(true) {
                        if(bufi == bufc) {
                            sb.append(buf, start, bufi - start);
                            fillBuf();
                            start = 0;
                            if(bufc == 0) break;
                        }

                        if(isDelimiter(buf[bufi])) break;
                        ++bufi;
                    }

                    sb.append(buf, start, bufi - start);

                    return sb.toString();
                } catch(IOException e) {
                    throw new RuntimeException("IO.next: Caught IOException.");
                }
            }

            public int nextInt() {
                try {
                    int ret = 0;

                    eatDelimiters();

                    boolean positive = true;
                    if(buf[bufi] == '-') {
                        ++bufi;
                        if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
                        positive = false;
                    }

                    boolean first = true;
                    while(true) {
                        if(!pumpBuf()) break;
                        if(isDelimiter(buf[bufi])) {
                            if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
                            break;
                        }
                        first = false;

                        if(buf[bufi] >= '0' && buf[bufi] <= '9') {
                            if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
                            ret *= 10;
                            ret -= (int)(buf[bufi] - '0');
                            if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
                        } else {
                            throw new RuntimeException("IO.nextInt: Invalid int.");
                        }

                        ++bufi;
                    }

                    if(positive) {
                        if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
                        ret = -ret;
                    }

                    return ret;
                } catch(IOException e) {
                    throw new RuntimeException("IO.nextInt: Caught IOException.");
                }
            }

            public long nextLong() {
                try {
                    long ret = 0;

                    eatDelimiters();

                    boolean positive = true;
                    if(buf[bufi] == '-') {
                        ++bufi;
                        if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
                        positive = false;
                    }

                    boolean first = true;
                    while(true) {
                        if(!pumpBuf()) break;
                        if(isDelimiter(buf[bufi])) {
                            if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
                            break;
                        }
                        first = false;

                        if(buf[bufi] >= '0' && buf[bufi] <= '9') {
                            if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
                            ret *= 10;
                            ret -= (long)(buf[bufi] - '0');
                            if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
                        } else {
                            throw new RuntimeException("IO.nextLong: Invalid long.");
                        }

                        ++bufi;
                    }

                    if(positive) {
                        if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
                        ret = -ret;
                    }

                    return ret;
                } catch(IOException e) {
                    throw new RuntimeException("IO.nextLong: Caught IOException.");
                }
            }

            public double nextDouble() {
                return Double.parseDouble(next());
            }

        }
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class C {

	static class Scanner{
		BufferedReader br=null;
		StringTokenizer tk=null;
		public Scanner(){
			br=new BufferedReader(new InputStreamReader(System.in));
		}
		public String next() throws IOException{
			while(tk==null || !tk.hasMoreTokens()) {
				String cad = br.readLine();
				if (cad == null)
					return null;
				tk=new StringTokenizer(cad);
			}
			return tk.nextToken();
		}
		public int nextInt() throws NumberFormatException, IOException{
			return Integer.valueOf(next());
		}
		public long nextLong() throws NumberFormatException, IOException{
			return Long.valueOf(next());
		}
		public double nextDouble() throws NumberFormatException, IOException{
			return Double.valueOf(next());
		}
	}

	static int N;
	static int[] array;
	static boolean[] visited;

	static int find(int index, int first, int count) {
		if (visited[index])
			return -1;
		visited[index] = true;
		if (count == N && index != first)
			return -1;
		if (index == first)
			return count;
		return find(array[index], first, count + 1);
	}

	static boolean test(int number, TreeSet<Integer> set) {
		for(int e: set) {
			int r = number % e;
			if (!(r == 0 || 2 * r == e))
				return false;
		}
		return true;
	}

	public static void main(String args[]) throws NumberFormatException, IOException {
		Scanner sc = new Scanner();
		N = sc.nextInt();
		array = new int[N];
		for(int i = 0; i < N; i++)
			array[i] = sc.nextInt() - 1;
		visited = new boolean[N];
		Arrays.fill(visited, false);
		TreeSet<Integer> tams = new TreeSet<Integer>();
		for(int i = 0; i < N; i++) {
			if (visited[i])
				continue;
			int ans = find(array[i], i, 1);
			if (ans == -1){
				System.out.println(-1);
				return;
			}
			if (ans > 1)
				tams.add(ans);
		}
		if (tams.size() == 0)
			System.out.println(1);
		else if (tams.size() == 1) {
			if (tams.first() % 2 == 0)
				System.out.println(tams.first() / 2);
			else
				System.out.println(tams.first());
		}
		else {
			int last = tams.pollLast();
			if (last % 2 == 0 && test(last/2, tams))
				System.out.println(last/2);
			else if (test(last, tams))
				System.out.println(last);
			else
				System.out.println(-1);
		}
	}

}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.StringTokenizer;

/**
 *
 * @author Public
 */
public class A741 {
    static int count=0;
     public static void main(String[] args) throws Exception{
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer(br.readLine());
        int n=Integer.parseInt(st.nextToken());

     LinkedList ad[]=new LinkedList[n];

   boolean visited[]=new boolean[n];
   Arrays.fill(visited,false);
   StringTokenizer st1=new StringTokenizer(br.readLine());
     for(int i=0;i<n;i++){
     ad[i]=new LinkedList();
     int k=Integer.parseInt(st1.nextToken());
     if(k-1!=i)
     ad[i].add(k-1);
     }
         int t=0;

   class dfs{
  void DFS(int x,boolean[] v){
      count++;
  v[x]=true;
  ListIterator itr= ad[x].listIterator();
  while(itr.hasNext()){
  int n=(int)itr.next();
   if(v[n]==false)
          DFS(n,v);
  }
  }
 }

     for(int i=0;i<n;i++){
      count=0;

  if(visited[i]==false){
     new dfs().DFS(i,visited);
         if((ad[count+i-1].isEmpty()) ){
             if(count==1)
             t=Math.max(t,1);
             else{ System.out.println(-1);
    return;    }}
         else if(count==2 && (int)ad[count+i-1].getFirst()==i) {t=Math.max(t,1);}
   else if((ad[count+i-1].isEmpty() && count!=1) ||((int)ad[count+i-1].getFirst()!=i)){
         System.out.println(-1);
    return;
   }
   else {
   t=Math.max(t,count);
   }
  }
         }

     System.out.println(t);
     }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Random;
import java.util.StringTokenizer;

public class A {
    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
        FastScanner sc = new FastScanner();

        int n = sc.nextInt();
        int[] crush = new int[n];
        for (int i = 0; i < n; i++) {
            crush[i] = sc.nextInt() - 1;
        }

        outer:
        for (int t = 1; t <= n*n; t++) {
            for (int x = 0; x < n; x++) {
                int y = get(t, x, crush);
                int xx = get(t, y, crush);
                if (x != xx) {
                    continue outer;
                }
            }
            System.out.println(t);
            return;
        }

        System.out.println(-1);
    }

    static int get(int t, int cur, int[] crush) {
        if (t == 0) {
            return cur;
        }
        return get(t - 1, crush[cur], crush);
    }

    static void shuffle(int[] arr) {
        Random rng = new Random();
        int length = arr.length;
        for (int idx = 0; idx < arr.length; idx++) {
            int toSwap = idx + rng.nextInt(length-idx);
            int tmp = arr[idx];
            arr[idx] = arr[toSwap];
            arr[toSwap] = tmp;
        }
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;
        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }
        public FastScanner() {
            this(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }
        long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextLong();
            }
            return a;
        }
    }
}

    import java.util.*;
        import java.math.*;
        import java.io.*;
        import java.text.DecimalFormat;
        import java.math.BigInteger;
        public class Main{
            //static int d=20;
            static long mod=1000000007 ;
            static HashMap<String,Double> hm=new HashMap<>();
            static ArrayList<ArrayList<Integer>> arr;
            static long[][] color;
            static int[] a;
            static int[] vis,num;
            static double val;
            public static void main(String[] args)  throws IOException {
                boolean online =false;
                String fileName = "C-large-practice";
                PrintWriter out;
                if (online) {
                    s.init(new FileInputStream(new File(fileName + ".in")));
                     out= new PrintWriter(new FileWriter(fileName + "out.txt"));
                }
                 else {
                    s.init(System.in);

                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
                }
                int n=s.ni();
                int[] a=new int[n];
                for(int i=0;i<n;i++)
                    a[i]=s.ni()-1;
                int[] cycle=new int[n];
                Arrays.fill(cycle,-1);
                int flag=0;
                int[] c=new int[n];
                Arrays.fill(c,-1);
                int ct=0;
               // int ans=-1;
                ArrayList<Integer> arr=new ArrayList<>();
                for(int i=0;i<n;i++){
                    if(c[i]!=-1)
                        continue;
                    int pre=i;
                    int sz=0;

                    while(c[i]==-1){
                        c[i]=ct;
                        i=a[i];
                        sz++;
                    }
                    ct++;

                    if(pre!=i && !(sz==1 && i!=a[i] )){
                        flag=1;
                        break;
                    }
                    if(sz%2==0)
                        sz/=2;
                    arr.add(sz);
                }
                if(flag==1 || arr.size()==0)
                    out.println(-1);

                else if(arr.size()==1)
                    out.println(arr.get(0));
                else{
                    long z=gcd(arr.get(0)*1L,arr.get(1)*1L);
                    long ans=(arr.get(0)*1L * arr.get(1)*1L)/z;
                    for(int i=2;i<arr.size();i++){
                        z=gcd(arr.get(i)*1L,ans);
                        ans=(arr.get(i)*1L * ans)/z;

                    }
                    out.println(ans);
                }
                out.close();

            }
            public static long gcd(long a,long b){
                if(a%b==0)
                    return b;
                else
                    return gcd(b,a%b);
            }
            public static long pow2(long a,long b){
                    long ans=1;
                    while(b>0){
                        if(b%2==1)
                            ans=(a*ans);
                        a=(a*a);
                        b/=2;
                    }
                    return  ans;
            }
            public static double pow3(double a,long b){
                    double ans=1;
                    while(b>0){
                        if(b%2==1)
                            ans=(a*ans);
                        a=(a*a);
                        b/=2;
                    }
                    return  ans;
            }

             static class name implements Comparable<name> {
                int id,p,g;
                public name(int  x,int y,int z){
                    id=x;
                    p=y;
                    g=z;
                }
                public int compareTo(name o){

                        return id-o.id;
                }
            }
            public static class s {
                static BufferedReader reader;
                static StringTokenizer tokenizer;

                /** call this method to initialize reader for InputStream */
                static void init(InputStream input) {
                    reader = new BufferedReader(
                                new InputStreamReader(input) );
                    tokenizer = new StringTokenizer("");
                }

                /** get next word */
                static String ns() throws IOException {
                    while ( ! tokenizer.hasMoreTokens() ) {
                        //TODO add check for eof if necessary
                        tokenizer = new StringTokenizer(
                            reader.readLine() );
                    }
                    return tokenizer.nextToken();
                }

                static int ni() throws IOException {
                    return Integer.parseInt( ns() );
                }

                static double nd() throws IOException {
                    return Double.parseDouble( ns() );
                }
                static long nl() throws IOException {
                    return Long.parseLong( ns() );
                }

            }
        }

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
import java.io.*;
public class codeforces
{
   static class Student{
       int x,y;
        Student(int x,int y){
            this.x=x;
            this.y=y;
            //this.z=z;
        }
    }
    static int prime[];
    static void sieveOfEratosthenes(int n)
    {
        // Create a boolean array "prime[0..n]" and initialize
        // all entries it as true. A value in prime[i] will
        // finally be false if i is Not a prime, else true.
        int pos=0;
        prime= new int[n+1];
        for(int p = 2; p*p <=n; p++)
        {
            // If prime[p] is not changed, then it is a prime
            if(prime[p] == 0)
            {
                // Update all multiples of p
                prime[p]=p;
                for(int i = p*p; i <= n; i += p)
                    prime[i] = p;
            }
        }
    }
static    class Sortbyroll implements Comparator<Student>
{
    // Used for sorting in ascending order of
    // roll number
    public int compare(Student c, Student b)
    {
        return c.x-b.x;
    }
}
static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

    static class Edge{
        int a,b;
        Edge(int a,int b){
            this.a=a;
            this.b=b;
        }
    }
    static class Trie{
        HashMap<Character,Trie>map;
         int c;
        Trie(){
            map=new HashMap<>();
            //z=null;
            //o=null;
            c=0;
        }
    }
    //static long ans;
    static int parent[];
    static int rank[];
    static int b[][];
    static int bo[];
    static int ho[];
    static int seg[];
    //static int pos;
   // static long mod=1000000007;
    //static int dp[][];
    static HashMap<Integer,Integer>map;
    static PriorityQueue<Student>q=new PriorityQueue<>();
    //static Stack<Integer>st;
   // static ArrayList<Character>ans;
    static ArrayList<ArrayList<Integer>>adj;
    static long ans;
    static Trie root;
    static long fac[];
    static long mod=(long)(1000000007);
    //static int ans;
    static void solve()throws IOException{
        FastReader sc=new FastReader();
        int n,x,pos=0,i,c;
        n=sc.nextInt();
        int a[]=new int[n+1];
        int b[]=new int[n+1];
        for(i=1;i<=n;i++)
            a[i]=sc.nextInt();
        for(i=1;i<=n;i++){
            b[a[i]]+=1;
        }
        for(i=1;i<=n;i++)
        {
            if(b[i]!=1){
                pos=1;
                break;
            }
        }
        if(pos==1)
            System.out.println(-1);
        else{
        HashMap<Integer,Integer>map=new HashMap<>();
        for(i=1;i<=n;i++){
            b[i]=0;
        }
            for(i=1;i<=n;i++){
                if(b[i]==1)
                    continue;
                c=1;
                x=a[i];
                while(x!=i){
                    b[x]=1;
                    ++c;
                    x=a[x];
                }
                if(c<=2)
                    map.put(1,1);
                else
                    map.put(c,1);
            }
            x=1;
            for(Integer k :map.keySet()){
                x=(x*k)/(int)gcd(x,k);
            }
            System.out.println(x);
        }
    }
    static void build(StringBuilder sb,int n,char a){
        if(n==0)
        {
            sb.append(a);
            return;
        }
        int x=(int)Math.sqrt(2*n);
        if(x*(x+1)>2*n)
            x-=1;
        for(int i=0;i<=x;i++)
            sb.append(a);
        n-=(x*(x+1))/2;
        build(sb,n,(char)((int)a+1));
    }
    static void dfs(Trie root,int k){
        if(root==null)
            return;
        for(char i='A';i<='Z';i++){
            if(root.map.containsKey(i)){
                ans+=root.map.get(i).c/k;
                dfs(root.map.get(i),k);
            }
        }
    }
    static long nCr(long n, long r,
                                    long p)
    {
        return (fac[(int)n]* modInverse(fac[(int)r], p)
                % p * modInverse(fac[(int)(n-r)], p)
                                    % p) % p;
    }
    //static int prime[];
    //static int dp[];
    public static void main(String[] args){
        //long sum=0;
        try {
                codeforces.solve();
                } catch (Exception e) {
                    e.printStackTrace();
                }
    }
       static long modInverse(long n, long p)
    {
        return power(n, p-(long)2,p);
    }
 static long power(long x, long y, long p)
{
    long res = 1;      // Initialize result

    x = x % p;  // Update x if it is more than or
                // equal to p

    while (y > 0)
    {
        // If y is odd, multiply x with result
        if (y %(long)2!=0)
            res = (res*x) % p;

        // y must be even now
        y = y>>1; // y = y/2
        x = (x*x) % p;
    }
    return res%p;
 }
    /*public static long power(long x,long a) {
		if(a==0) return 1;
		if(a%2==1)return (x*1L*power(x,a-1))%mod;
		return (power((int)((x*1L*x)%mod),a/2))%mod;
	}*/
   static int find(int x)
    {
        // Finds the representative of the set
        // that x is an element of
        while(parent[x]!=x)
        {
            // if x is not the parent of itself
            // Then x is not the representative of
            // his set,
            x=parent[x];

            // so we recursively call Find on its parent
            // and move i's node directly under the
            // representative of this set
        }

        return x;
    }
    static void union(int x, int y)
    {
        // Find representatives of two sets
        int xRoot = find(x), yRoot = find(y);

        // Elements are in the same set, no need
        // to unite anything.
        if (xRoot == yRoot)
            return;

         // If x's rank is less than y's rank
        if (rank[xRoot] < rank[yRoot])

            // Then move x under y  so that depth
            // of tree remains less
            parent[xRoot] = yRoot;

        // Else if y's rank is less than x's rank
        else if (rank[yRoot] < rank[xRoot])

            // Then move y under x so that depth of
            // tree remains less
            parent[yRoot] = xRoot;

        else // if ranks are the same
        {
            // Then move y under x (doesn't matter
            // which one goes where)
            parent[yRoot] = xRoot;

            // And increment the the result tree's
            // rank by 1
            rank[xRoot] = rank[xRoot] + 1;
        }
    }
    static long gcd(long a, long b)
    {
        if (a == 0){
             //ans+=b;
            return b;
        }
        return gcd(b % a, a);
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import java.util.*;

public class A_GENERAL {

	// for fast output printing  : use printwriter or stringbuilder
	// remember to close pw using pw.close()
	static StringBuilder sb = new StringBuilder();
	static long seive_size = (long) 1e6;
	static String alpha = "abcdefghijklmnopqrstuvwxyz";
    static ArrayList<Integer> primes = new ArrayList<>();
    static boolean[] set = new boolean[(int) seive_size+1];
    static int n, m, k;
    static ArrayList<Integer>[] adj;
    static boolean[] visited;
    static ArrayDeque<Integer> q = new ArrayDeque<>();
    static final long MOD = 998244353;
    static int[] dx = new int[] {1, 0, -1, 0, 1, 1, -1, -1};
    static int[] dy = new int[] {0, 1, 0, -1, 1, -1, 1, -1};
    static long[][] arr;
    static int[] rank;
    static int[] parent;

    static int[] p;
    static int res = 0;
    public static void main(String[] args) {
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		MyScanner sc = new MyScanner();
		n = sc.nextInt();
		init(n);
		p = new int[n+1];
		for(int i = 1; i <= n; i++) {
			p[i] = sc.nextInt();
		}
		boolean flag = true;
		long ans = 1;
		for(int i = 1; i <= n; i++) {
			res = 1;
			visited = new boolean[n+1];
			visited[i] = true;
			flag &= dfs(p[i], i);
			if(res == 2) res = 1;
			ans = (ans*res)/gcd(ans, res);
			if(!flag) {
				System.out.println(-1);
				return;
			}
		}
		System.out.println(ans);
		out.close();
	}
	public static boolean dfs(int u, int s) {
		if(u == s) {
			return true;
		}
		if(visited[u]) return false;
		visited[u] = true;
		res++;
		return dfs(p[u], s);
	}

	public static class Triplet implements Comparable<Triplet> {
		int x;
    	int y;
    	int z;
    	Triplet(int x, int y, int z) {
    		this.x = x;
    		this.y = y;
    		this.z = z;
    	}
    	public int compareTo(Triplet o) {
    		return Integer.compare(this.x, o.x);
    	}
    }
	public static class Pair implements Comparable<Pair>{
		long f;
		long s;
		Pair(long f, long s) {
			this.f = f;
			this.s = s;
		}
		public int compareTo(Pair o) {
			return Long.compare(this.f, o.f);
		}
	}
	public static void init(int n) {
    	adj = new ArrayList[n+1];
    	visited = new boolean[n+1];
    	parent = new int[n+1];
		rank = new int[n+1];
    	for(int i = 0; i <= n; i++) {
    		adj[i] = new ArrayList();
    		parent[i] = i;
			rank[i] = 0;
    	}
    }
	// print string "s" multiple times
	// prefer to use this function for multiple printing
	public static String mp(String s, int times) {
		return String.valueOf(new char[times]).replace("\0", s);
	}
	// take log with base 2
 	public static long log2(long k) {
 		return 63-Long.numberOfLeadingZeros(k);
 	}

 	// using lambda function for sorting
   	public static void lambdaSort() {
   		Arrays.sort(arr, (a, b) -> Double.compare(a[0], b[0]));
   	}

  	// (n choose k) = (n/k) * ((n-1) choose (k-1))
  	public static long choose(long n, long k) {
 		return (k == 0) ? 1 : (n*choose(n-1, k-1))/k;
 	}

 	// just for keeping gcd function for other personal purposes
 	public static long gcd(long a, long b) {
 		return (a == 0) ? b : gcd(b%a, a);
 	}

	public static long max(long... as) {
        long max = Long.MIN_VALUE;
        for (long a : as) max = Math.max(a, max);
        return max;
    }

    public static long min(int... as) {
        long min = Long.MAX_VALUE;
        for (long a : as) min = Math.min(a, min);
        return min;
    }

    public static long modpow(long x, long n, long mod) {
    	if(n == 0) return 1%mod;
    	long u = modpow(x, n/2, mod);
    	u = (u*u)%mod;
    	if(n%2 == 1) u = (u*x)%mod;
    	return u;
    }
 	// ======================= binary search (lower and upper bound) =======================
	public static int lowerBound(long[] a, int x) {
		int lo = 0;
 		int hi = a.length-1;
 		int ans = -1;
 		while(lo <= hi) {
 			int mid = (lo+hi)/2;
 			if(x < a[mid]) {
 				hi = mid-1;
 			} else if(x > a[mid]) {
 				lo = mid+1;
 			} else if(lo != hi) {
 				 hi = mid-1; 		// for first occurrence
 				 ans = mid;
 			} else {
 				return mid;
 			}
 		}
 		return ans;
	}

	public static int upperBound(long[] a, long x) {
		int lo = 0;
		int hi = a.length-1;
		int ans = -1;
		while(lo <= hi) {
			int mid = (lo+hi)/2;
			if(x < a[mid]) {
				hi = mid-1;
			} else if(x > a[mid]) {
				lo = mid+1;
			} else if(lo != hi) {
				lo = mid+1;			// for last occurrence
				ans = mid;
			} else {
				return mid;
			}
		}
		return ans;
	}
	// ================================================================

	// ================== SEIVE OF ERATOSTHENES =======================
	// Complexity : O(N * log(log(N)))       ( almost O(N) )
	public static void generatePrimes() {
		// set.add(0);
		// set.add(1);
		Arrays.fill(set, true);
		set[0] = false;
		set[1] = false;
		for(int i = 2; i <= seive_size; i++) {
			if(set[i]) {
				for(long j = (long) i*i; j <= seive_size; j+=i)
					set[(int)j] = false;
				primes.add(i);
			}
		}
	}

	public static boolean isPrime(long N) {
		if(N <= seive_size) return set[(int)N];
		for (int i = 0; i < (int)primes.size(); i++)
			if (N % primes.get(i) == 0) return false;
		return true;
	}
	// ===========================================================

 	// ================ Permutation of String ====================
 	public static void permute(String str) {
 		permute(str, 0, str.length()-1);
 	}
 	public static void permute(String str, int l, int r)
    {
        if (l == r)
            System.out.println(str);
        else
        {
            for (int i = l; i <= r; i++)
            {
                str = swap(str,l,i);
                permute(str, l+1, r);
                str = swap(str,l,i);
            }
        }
    }
	public static String swap(String a, int i, int j)
    {
        char temp;
        char[] charArray = a.toCharArray();
        temp = charArray[i] ;
        charArray[i] = charArray[j];
        charArray[j] = temp;
        return String.valueOf(charArray);
    }
	// Union-find
	// static int[] parent, rank;
//	public static void makeSet(int n) {
//
//		parent = new int[n+1];
//		rank = new int[n+1];
//		for(int i = 1; i <= n; i++) {
//			parent[i] = i;
//			rank[i] = 0;
//		}
//	}
	public static int find(int u) {

		if(parent[u] == u)	return u;

		int v = find(parent[u]);
		parent[u] = v;
		return v;

	}
	public static boolean connected(int u, int v) {
		return find(u) == find(v);
	}
	public static void Union(int u, int v) {

		int x = find(u);				//root of u
		int y = find(v);				//root of v

		if(x == y)		return;
		if(rank[x] == rank[y]) {
			parent[y] = x;
			rank[x]++;
		}
		else if(rank[x] > rank[y]) {
			parent[y] = x;
		}
		else {
			parent[x] = y;
		}

	}

//	public static int dijkstra(int x, int y) {
//    	int[] dist = new int[n+1];
//    	Arrays.fill(dist, Integer.MAX_VALUE);
//    	PriorityQueue<Node> q = new PriorityQueue<>();
//    	q.add(new Node(x, 0));
//    	dist[x] = 0;
//    	while(!q.isEmpty()) {
//    		Node node = q.poll();
//    		int u = node.key;
//    		if(u == y) {
//    			break;
//    		}
//    		for(int v : res[u]) {
//    			if(dist[v] > dist[u]+count[u]) {
//    				dist[v] = dist[u] + count[u];
//    				q.add(new Node(v, dist[v]));
//    			}
//    		}
//    	}
//    	if(dist[y] == Integer.MAX_VALUE) {
//    		return -1;
//    	}
//    	return dist[y];
//    }

	public static class MyScanner {
		BufferedReader br;
		StringTokenizer st;
		public MyScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		String next() {while (st == null || !st.hasMoreElements()) {
			try {st = new StringTokenizer(br.readLine());}
			catch (IOException e) {e.printStackTrace();}}
		return st.nextToken();}
		int nextInt() {return Integer.parseInt(next());}
		long nextLong() {return Long.parseLong(next());}
		double nextDouble() {return Double.parseDouble(next());}
		String nextLine(){String str = "";
		try {str = br.readLine();}
		catch (IOException e) {e.printStackTrace();}
		return str;}
		int[] nextIntArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        int[] nextIntArray(int n, int delta) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt() + delta;
            return a;
        }

        long[] nextLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++)
                a[i] = nextLong();
            return a;
        }
	}

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int crushes[] = in.readIntArray(n);
            for (int i = 0; i < crushes.length; i++) {
                crushes[i] -= 1;
            }
            for (int t = 1; t <= 2 * n + 5; t++) {
                boolean isPos = true;
                for (int i = 0; i < n; i++) {
                    int y = getEnd(i, t, crushes);
                    int x = getEnd(y, t, crushes);
                    if (x != i) {
                        isPos = false;
                        break;
                    }
                }
                if (isPos) {
                    out.println(t);
                    return;
                }
            }
            out.println(-1);
        }

        private int getEnd(int st, int t, int crushes[]) {
            if (t == 0) {
                return st;
            } else {
                return getEnd(crushes[st], t - 1, crushes);
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        private boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public int[] readIntArray(int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++)
                array[i] = readInt();
            return array;
        }

        public int nextInt() {
            return readInt();
        }

    }
}

import java.io.*;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;

public class C {

    final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void solve() throws IOException {
        int n = readInt();
        int[] crush = new int[n];
        int[] count = new int[n];
        for(int i = 0; i < n; i++) {
            crush[i] = readInt() - 1;
            count[crush[i]]++;
        }

        if(Arrays.stream(count).anyMatch(x -> x != 1)) {
            out.println(-1);
            return;
        }
        long res = 1;
        boolean[] used = new boolean[n];
        for(int i = 0; i < n; i++) {
            if(used[i]) continue;

            int cur = i;
            int step = 0;
            while (true) {
                used[cur] = true;
                step++;
                cur = crush[cur];
                if(cur == i) break;
            }
            while (step % 2 == 0) step /= 2;
            long gcd = gcd(res, step);
            res *= step / gcd;
        }
        out.println(res);
    }
    long gcd(long a, long b) {
        if(a == 0) return b;
        if(b == 0) return a;
        if(a > b) return gcd(a%b, b);
        else return gcd(a, b % a);
    }

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    int[] readArr(int n) throws IOException {
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = readInt();
        }
        return res;
    }

    long[] readArrL(int n) throws IOException {
        long[] res = new long[n];
        for (int i = 0; i < n; i++) {
            res[i] = readLong();
        }
        return res;
    }

    public static void main(String[] args) {
        new C().run();
    }

    public void run() {
        try {
            long t1 = System.currentTimeMillis();
            init();
            solve();
            out.close();
            long t2 = System.currentTimeMillis();
            System.err.println("Time = " + (t2 - t1));
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }
}

import java.util.*;

public class A741 {

	public static void main(String[] args){

		int n;

		Scanner scan=new Scanner(System.in);

		n=scan.nextInt();

		int[] arr= new int[n];

		for(int i=0;i<n;i++){
			arr[i]=scan.nextInt();
		}

		boolean[] tv=new boolean[n];

		int i=0;
		int max=1;

		for(;i<n;i++){
			if(!tv[i]){

				ArrayList<Integer> al=new ArrayList<>();

				al.add(i+1);
				int res=0;

				while(!tv[i]){

					al.add(arr[i]);
					tv[i]=true;
					i=arr[i]-1;

				}

				if(al.get(0)==al.get(al.size()-1))
				{
					res=al.size()-1;

					if(res==2)
						res=1;

					max*=res;

				}

				else {

					System.out.println("-1");
					return;
				}

			}

		}

		System.out.println(max);
	}
}

import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class Main
{
@SuppressWarnings("unchecked")
public static void main (String[] args) throws java.lang.Exception
{
//BufferedReader in=new BufferedReader(new FileReader(".\\mmk\\test\\A-small-attempt0.in"));
//PrintWriter out=new PrintWriter(".\\mmk\\test\\output.txt");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);

int n,i,max_t,cnt,cur;
boolean exists;

n=Integer.parseInt(in.readLine());

int[] a=new int[n];
boolean[] found;

StringTokenizer st=new StringTokenizer(in.readLine());

for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(st.nextToken())-1;
}

exists=true;
max_t=0;

for(i=0;i<n;i++)
{
found=new boolean[n];
cur=i;
found[cur]=true;
cnt=0;

do
{
found[cur]=true;
cnt++;
cur=a[cur];
}while(!found[cur]);

if(cur==i)
{
    if(cnt==2)
        cnt--;

    max_t=Math.max(max_t,cnt);
}
else
{
    exists=false;
    break;
}

}

if(!exists)
    out.println(-1);
else
    out.println(max_t);

out.flush();
out.close();
}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

import static java.util.Arrays.binarySearch;

/**
 * @author andrey
 */
public class C {

    private static StringTokenizer tok;
    private static BufferedReader reader;

    private static String nextToken() throws IOException {
        while (tok == null || !tok.hasMoreTokens()) {
            tok = new StringTokenizer(reader.readLine());
        }
        return tok.nextToken();
    }

    private static int nextInteger() throws IOException {
        return Integer.parseInt(nextToken());
    }

    private static long nextLong() throws IOException {
        return Integer.parseInt(nextToken());
    }

    private static boolean[] used;
    private static int[] crush;

    private static long gcd(long a, long b) {
        if (b==0) return a;
        return gcd(b,a % b);
    }

    private static long lcm(long a, long b) {
        return a * (b / gcd(a, b));
    }

    private static int dfs(int cur, int root, int deep) {
        int next = crush[cur];
        if (next == root) {
            return deep;
        }
        if (used[next]) {
            return -1;
        }
        used[next] = true;
        return dfs(next, root, deep + 1);
    }

    public static void main(String[] args) throws IOException {
        reader = new BufferedReader(new InputStreamReader(System.in));

        final int n = nextInteger();

        crush = new int[n];
        used = new boolean[n];

        for (int i = 0; i < n; i++) {
            crush[i] = nextInteger() - 1;
        }

        boolean allSmall = true;
        List<Integer> lens = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (!used[i]) {
                used[i] = true;
                int len = dfs(i, i, 1);
                if (len == -1) {
                    System.out.println(-1);
                    return;
                }
                allSmall &= len <= 2;
                lens.add(len);
            }
        }

        if (allSmall) {
            System.out.println(1);
            return;
        }

        long result = lens.get(0);
        for (int i = 1; i < lens.size(); i++) {
            result = lcm(result, lens.get(i));
        }

        System.out.println(result);
    }
}

import java.util.*;
import java.io.*;

public class Main
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int[] crushes = new int[Integer.parseInt(br.readLine())];
		boolean[] visited = new boolean[crushes.length];

		StringTokenizer st = new StringTokenizer(br.readLine());
		for (int i = 0; i < crushes.length; i++)
		{
			crushes[i] = Integer.parseInt(st.nextToken()) - 1;
		}

		int max = -1;

		for (int i = 0; i < crushes.length; i++)
		{
			if(!visited[i])
			{
				int cnt = 1;

				visited[i] = true;
				int idx = crushes[i];

				while(idx != i && !visited[idx])
				{
					visited[idx] = true;
					idx = crushes[idx];

					cnt++;
				}

				if(idx == i)
				{
					if(cnt % 2 == 0)
						cnt /= 2;

					if(max < cnt)
						max = cnt;
				}
				else
				{
					max = -1;
					break;
				}
			}
		}

		System.out.println(max);
	}
}

import java.io.*;
import java.util.*;

public class Main {
    static FastScanner in;
    static int n;
    static int c[], ins[];
    static int ans = 1;
    static Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    public static void main(String[] args) throws IOException {
        //      Scanner in = new Scanner(new File("input.txt"));
        //        Scanner in = new Scanner(System.in);
        //        in = new FastScanner("input.txt");
        in = new FastScanner(System.in);
        n = in.nextInt();
        c = new int[n + 1];
        ins = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            c[i] = in.nextInt();
            ins[c[i]]++;
            map.put(i, c[i]);
        }
        for (int i = 1; i <= n; i++) {
            if (ins[c[i]] != 1)
                ans = -1;
        }
        if (ans == -1) {
            System.out.println(ans);
        } else {
            boolean isVisited[] = new boolean[n + 1];
            List<Integer> lis = new ArrayList<Integer>();
            for (int i = 1; i <= n; i++) {
                Stack<Integer> st = new Stack<Integer>();
                int con = 0;
                if (!isVisited[i]) {
                    st.push(i);
                }
                while (!st.isEmpty()) {
                    int item = st.pop();
                    isVisited[item] = true;
                    int j = map.get(item);
                    if (!isVisited[j]) {
                        st.push(j);
                    }
                    con++;
                }
                lis.add(con);
            }
            Collections.sort(lis);
            int ans = 1;
            for (int j : lis) {
                if (j != 0)
                    ans = lcm(j, ans);
            }
            if (ans == 2)
                System.out.println(1);
            else
                System.out.println(ans);
        }
    }

    static int lcm(int a, int b) {
        return a * b / gcd(a, b);
    }

    static int gcd(int a, int b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
}

class FastScanner {

    BufferedReader br;
    StringTokenizer tokenizer;

    FastScanner(String fileName) throws FileNotFoundException {
        this(new FileInputStream(new File(fileName)));
    }

    FastScanner(InputStream is) {
        br = new BufferedReader(new InputStreamReader(is));
    }

    String nextLine() throws IOException {
        tokenizer = null;
        return br.readLine();
    }

    String next() throws IOException {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            String line = br.readLine();
            if (line == null) {
                return null;
            }
            tokenizer = new StringTokenizer(line);
        }
        return tokenizer.nextToken();
    }

    int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    char nextChar() throws IOException {
        return next().charAt(0);
    }
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        ConsoleIO io = new ConsoleIO();
        new Main(io).solve();
        io.close();
    }
    ConsoleIO io;
    Main(ConsoleIO io) {
        this.io = io;
    }

    long MOD = 1_000_000_007;
    int N, M, K, Q;

    public void solve() {
        int n = io.ri();
        int[] map = new int[n];
        for(int i = 0;i<n;i++){
            int v = io.ri()-1;
            map[i] = v;
        }

        boolean[] used = new boolean[n];
        long res = 1;
        long div = 0;
        int k = 0;
        for(int i = 0;i<n;i++){
            if(!used[i]){
                int t = i;
                used[t] = true;
                int cur=map[i];
                int c = 1;
                while(!used[cur]){
                    c++;
                    used[cur] =true;
                    cur = map[cur];
                }
                if(cur!=t){
                    io.writeLine("-1");
                    return;
                }
                k++;
                if(c%2==0)c/=2;
                res*=c;
                div = gcd(div, c);
            }
        }

        if(k>1)res/=div;

        io.writeLine(res + "");
    }

    long gcd(long a, long b) {
        if (a < b) return gcd(b, a);
        return b == 0 ? a : gcd(b, a % b);
    }

}

class ConsoleIO {
    BufferedReader br;
    PrintWriter out;
    public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);}
    public void flush(){this.out.flush();}
    public void close(){this.out.close();}
    public void writeLine(String s) {this.out.println(s);}
    public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
    public void writeWord(String s){
        this.out.print(s);
    }
    public void writeIntArray(int[] a, int k, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < k; i++) {
            if (i > 0) sb.append(separator);
            sb.append(a[i]);
        }
        this.writeLine(sb.toString());
    }
    public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
    public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
    public long[] readLongArray() {
        String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
        for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
        return r;
    }
    public int[] readIntArray() {
        String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
        for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
        return r;
    }
    public int[] readIntArray(int n) {
        int[] res = new int[n];
        char[] all = this.readLine().toCharArray();
        int cur = 0;boolean have = false;
        int k = 0;
        boolean neg = false;
        for(int i = 0;i<all.length;i++){
            if(all[i]>='0' && all[i]<='9'){
                cur = cur*10+all[i]-'0';
                have = true;
            }else if(all[i]=='-') {
                neg = true;
            }
            else if(have){
                res[k++] = neg?-cur:cur;
                cur = 0;
                have = false;
                neg = false;
            }
        }
        if(have)res[k++] = neg?-cur:cur;
        return res;
    }
    public int ri() {
        try {
            int r = 0;
            boolean start = false;
            boolean neg = false;
            while (true) {
                int c = br.read();
                if (c >= '0' && c <= '9') {
                    r = r * 10 + c - '0';
                    start = true;
                } else if (!start && c == '-') {
                    start = true;
                    neg = true;
                } else if (start || c == -1) return neg ? -r : r;
            }
        } catch (Exception ex) {
            return -1;
        }
    }
    public long readLong() {
        try {
            long r = 0;
            boolean start = false;
            boolean neg = false;
            while (true) {
                int c = br.read();
                if (c >= '0' && c <= '9') {
                    r = r * 10 + c - '0';
                    start = true;
                } else if (!start && c == '-') {
                    start = true;
                    neg = true;
                } else if (start || c == -1) return neg ? -r : r;
            }
        } catch (Exception ex) {
            return -1;
        }
    }
    public String readWord() {
        try {
            boolean start = false;
            StringBuilder sb = new StringBuilder();
            while (true) {
                int c = br.read();
                if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') {
                    sb.append((char)c);
                    start = true;
                } else if (start || c == -1) return sb.toString();
            }
        } catch (Exception ex) {
            return "";
        }
    }
    public char readSymbol() {
        try {
            while (true) {
                int c = br.read();
                if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
                    return (char) c;
                }
            }
        } catch (Exception ex) {
            return 0;
        }
    }
    public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }}
}
class Pair {
    public Pair(int a, int b) {this.a = a;this.b = b;}
    public int a;
    public int b;
}
class Tri {
    public Tri(int a, int b, int c) {this.a = a;this.b = b;this.c = c;}
    public int a;
    public int b;
    public int c;
}
class PairLL {
    public PairLL(long a, long b) {this.a = a;this.b = b;}
    public long a;
    public long b;
}

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

public class ArpasLoudOwfAndMehrdadsEvilPlan {
    InputStream is;
    PrintWriter pw;
    String INPUT = "";
    long L_INF = (1L << 60L);

    void solve() {
        int n = ni(), m;
        int a[] = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            a[i] = ni();
        }
        boolean visited[] = new boolean[n + 1];
        int t = 1,x=-1;
        Set<Long> l = new HashSet<>();
        for (int i = 1; i <= n; i++) {
            if(!visited[i] && a[i]==i)
                continue;
            if(!visited[i]){
                x= dfs(i,a,visited);
                l.add((long) x);
            }
            if(x==-1){
                pw.println(-1);
                return;
            }
        }
        pw.println(findLCM(l));
    }

    private long findLCM(Set<Long> l) {
        long a=1;
        for (Long b : l) {
            long hcf = gcd(a,b);
            a = (a*b)/hcf;
        }
        return a;
    }

    long gcd(long a, long b) {
        while (a != 0 && b != 0) {
            if (a > b) {
                a %= b;
            } else {
                b %= a;
            }
        }
        return Math.max(a, b);
    }

    private int dfs(int i, int[] a, boolean[] visited) {
        int head = i,count=0;
//        System.out.println("start "+i);
        Set<Integer> st = new HashSet<>();
        while(!st.contains(i)){
//            System.out.println("loop "+i);
            st.add(i);
            visited[i]=true;
            i=a[i];
            if(a[i]==i)
                return -1;
            count++;
        }
//        System.out.println(st);
        visited[i]=true;
        Set<Integer> st2 = new HashSet<>();
        for (int j = 0; j < st.size(); j++) {
            st2.add(i);
            i=a[i];
        }
        if(st.size()!=st2.size())
            return -1;
        return st.size()==2?1:st.size();
    }

    void run() throws Exception {
        //		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        is = System.in;
        pw = new PrintWriter(System.out);

        long s = System.currentTimeMillis();
        //        int t = ni();
        //        while (t-- > 0)
        solve();
        pw.flush();
        tr(System.currentTimeMillis() - s + "ms");
    }

    public static void main(String[] args) throws Exception {
        new ArpasLoudOwfAndMehrdadsEvilPlan().run();
    }

    private byte[] inbuf = new byte[1024];
    private int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (!oj) System.out.println(Arrays.deepToString(o));
    }
}

import java.util.*;
import java.io.*;
import java.awt.geom.*;
import java.math.*;

public class C {

	static final Scanner in = new Scanner(System.in);
	static final PrintWriter out = new PrintWriter(System.out,false);
	static boolean debug = false;

	static boolean[] visited;
	static int n;
	static int[] a;

	static int rec(int cur) {
		if (visited[cur]) return 0;
		visited[cur] = true;
		return rec(a[cur]) + 1;
	}

	static void solve() {
		n = in.nextInt();
		a = new int[n];
		boolean[] f = new boolean[n];
		for (int i=0; i<n; i++) {
			a[i] = in.nextInt() - 1;
			if (f[a[i]]) {
				out.println("-1");
				return;
			}
			f[a[i]] = true;
		}
		visited = new boolean[n];
		int ans = -1;
		for (int i=0; i<n; i++) {
			if (!visited[i]) {
				int tmp = rec(i);
				ans = Math.max(ans, tmp == 2 ? 1 : tmp);
			}
		}

		out.println(ans);
	}

	public static void main(String[] args) {
		debug = args.length > 0;
		long start = System.nanoTime();

		solve();
		out.flush();

		long end = System.nanoTime();
		dump((end - start) / 1000000 + " ms");
		in.close();
		out.close();
	}

	static void dump(Object... o) { if (debug) System.err.println(Arrays.deepToString(o)); }
}

import java.io.*;
import java.util.*;

public class Main {
    static FastScanner in;
    static int n;
    static int c[], ins[];
    static int ans = 1;
    static Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    public static void main(String[] args) throws IOException {
        //      Scanner in = new Scanner(new File("input.txt"));
        //        Scanner in = new Scanner(System.in);
        //        in = new FastScanner("input.txt");
        in = new FastScanner(System.in);
        n = in.nextInt();
        c = new int[n + 1];
        ins = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            c[i] = in.nextInt();
            ins[c[i]]++;
            map.put(i, c[i]);
        }
        for (int i = 1; i <= n; i++) {
            if (ins[i] != 1)
                ans = -1;
        }
        if (ans == -1) {
            System.out.println(ans);
        } else {
            boolean isVisited[] = new boolean[n + 1];
            List<Integer> lis = new ArrayList<Integer>();
            for (int i = 1; i <= n; i++) {
                Stack<Integer> st = new Stack<Integer>();
                int con = 0;
                if (!isVisited[i]) {
                    st.push(i);
                }
                while (!st.isEmpty()) {
                    int item = st.pop();
                    isVisited[item] = true;
                    int j = map.get(item);
                    if (!isVisited[j]) {
                        st.push(j);
                    }
                    con++;
                }
                lis.add(con);
            }
            Collections.sort(lis);
            int ans = 1;
            for (int j : lis) {
                if (j != 0 && j != 2)
                    ans = lcm(j, ans);
            }
            if (ans == 2)
                System.out.println(1);
            else
                System.out.println(ans);
        }
    }

    static int lcm(int a, int b) {
        return a * b / gcd(a, b);
    }

    static int gcd(int a, int b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
}

class FastScanner {

    BufferedReader br;
    StringTokenizer tokenizer;

    FastScanner(String fileName) throws FileNotFoundException {
        this(new FileInputStream(new File(fileName)));
    }

    FastScanner(InputStream is) {
        br = new BufferedReader(new InputStreamReader(is));
    }

    String nextLine() throws IOException {
        tokenizer = null;
        return br.readLine();
    }

    String next() throws IOException {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            String line = br.readLine();
            if (line == null) {
                return null;
            }
            tokenizer = new StringTokenizer(line);
        }
        return tokenizer.nextToken();
    }

    int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    char nextChar() throws IOException {
        return next().charAt(0);
    }
}

import java.util.Scanner;

public class CodeForces
{
	public static void main(String[] args)
	{
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int[] arr = new int[n];
		for (int i = 0; i < n; i++)
			arr[i] = scan.nextInt()-1;
		boolean good = true;
		boolean[] vis = new boolean[n];
		long ans = 1;
		for (int i = 0; good && i < n; i++)
		{
			if (vis[i])
				continue;
			vis[i] = true;
			int p = arr[i];
			int count = 1;
			boolean cycle = false;
			while (count <= n)
			{
				if (i == p)
				{
					cycle = true;
					break;
				}
				vis[p] = true;
				p = arr[p];
				count++;
			}
			if (!cycle)
			{
				good = false;
				break;
			}
			if (count == 2)
				count = 1;
			ans = lcm(ans, count);
		}
		System.out.println(good ? ans : -1);
	}

	private static long lcm(long a, long b)
	{
		return a/gcd(a, b) * b;
	}

	private static long gcd(long a, long b)
	{
		return b == 0 ? a : gcd(b, a%b);
	}
}

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.*;

public class C{
	static long mod=1000000007;
	static ArrayList<Integer>[]ar;
    public static void main(String[] args) throws Exception{
    	InputReader in = new InputReader(System.in);
    	PrintWriter pw=new PrintWriter(System.out);

    	//int t=in.readInt();
        //while(t-->0)
        //{

        int n=in.readInt();
        ar=new ArrayList[n];

    	//long n=in.readLong();
    	int a[]=new int[n];
    	for(int i=0;i<n;i++)
    	ar[i]=new ArrayList<Integer>();
    	for(int i=0;i<n;i++)
    	{
    		a[i]=in.readInt()-1;
    		ar[i].add(a[i]);
    	}
    	int min=-1;
    	for(int t=1;t<=100;t++)
    	{
    		int f=1;
    		for(int i=0;i<n;i++)
    		{
    			int c=t;
    			int pos=i;

    			while(c>0)
    			{
    				pos=a[pos];
    				c--;
    			}
    			int spos=pos;
    			c=t;
    			while(c>0)
    			{
    				spos=a[spos];
    				c--;
    			}
    			if(spos!=i)
    			{
    				f=0;
    				break;
    			}
    		}
    		if(f==1)
    		{
    			min=t;
    			break;
    		}
    	}

    	//String a=in.readString();

		pw.println(min);

    	//}

    	pw.close();
    }

public static long gcd(long x,long y)
{
	if(x%y==0)
		return y;
	else
		return gcd(y,x%y);
}
public static int gcd(int x,int y)
{
	if(x%y==0)
		return y;
	else
		return gcd(y,x%y);
}
public static int abs(int a,int b)
{
	return (int)Math.abs(a-b);
}
public static long abs(long a,long b)
{
	return (long)Math.abs(a-b);
}
public static int max(int a,int b)
{
	if(a>b)
		return a;
	else
		return b;
}
public static int min(int a,int b)
{
	if(a>b)
		return b;
	else
		return a;
}
public static long max(long a,long b)
{
	if(a>b)
		return a;
	else
		return b;
}
public static long min(long a,long b)
{
	if(a>b)
		return b;
	else
		return a;
}

public static long pow(long n,long p,long m)
{
	 long  result = 1;
	  if(p==0)
	    return 1;
	if (p==1)
	    return n;
	while(p!=0)
	{
	    if(p%2==1)
	        result *= n;
	    if(result>=m)
	    result%=m;
	    p >>=1;
	    n*=n;
	    if(n>=m)
	    n%=m;
	}
	return result;
}
public static long pow(long n,long p)
{
	long  result = 1;
	  if(p==0)
	    return 1;
	if (p==1)
	    return n;
	while(p!=0)
	{
	    if(p%2==1)
	        result *= n;
	    p >>=1;
	    n*=n;
	}
	return result;

}
static class Pair implements Comparable<Pair>
{
	int a,b;
	Pair (int a,int b)
	{
		this.a=a;
		this.b=b;
	}

	public int compareTo(Pair o) {
		// TODO Auto-generated method stub
		if(this.a!=o.a)
		return Integer.compare(this.a,o.a);
		else
			return Integer.compare(this.b, o.b);
		//return 0;
	}
	public boolean equals(Object o) {
        if (o instanceof Pair) {
            Pair p = (Pair)o;
            return p.a == a && p.b == b;
        }
        return false;
    }
    public int hashCode() {
        return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
    }

}

static long sort(int a[])
{  int n=a.length;
	int b[]=new int[n];
	return mergeSort(a,b,0,n-1);}
static long mergeSort(int a[],int b[],long left,long right)
{ long c=0;if(left<right)
 {   long mid=left+(right-left)/2;
	 c= mergeSort(a,b,left,mid);
	 c+=mergeSort(a,b,mid+1,right);
	 c+=merge(a,b,left,mid+1,right); }
	return c;	 }
static long merge(int a[],int  b[],long left,long mid,long right)
{long c=0;int i=(int)left;int j=(int)mid; int k=(int)left;
while(i<=(int)mid-1&&j<=(int)right)
{ if(a[i]<=a[j]) {b[k++]=a[i++]; }
else	{ b[k++]=a[j++];c+=mid-i;}}
while (i <= (int)mid - 1)   b[k++] = a[i++];
while (j <= (int)right) b[k++] = a[j++];
for (i=(int)left; i <= (int)right; i++)
	a[i] = b[i];  return c;  }

public static int[] radixSort(int[] f)
{
	int[] to = new int[f.length];
	{
		int[] b = new int[65537];
		for(int i = 0;i < f.length;i++)b[1+(f[i]&0xffff)]++;
		for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
		for(int i = 0;i < f.length;i++)to[b[f[i]&0xffff]++] = f[i];
		int[] d = f; f = to;to = d;
	}
	{
		int[] b = new int[65537];
		for(int i = 0;i < f.length;i++)b[1+(f[i]>>>16)]++;
		for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
		for(int i = 0;i < f.length;i++)to[b[f[i]>>>16]++] = f[i];
		int[] d = f; f = to;to = d;
	}
	return f;
}
static  class InputReader
{
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public InputReader(InputStream stream)
    {
        this.stream = stream;
    }

    public int read()
    {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars)
        {
            curChar = 0;
            try
            {
                numChars = stream.read(buf);
            } catch (IOException e)
            {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-')
        {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do
        {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }
    public String readLine() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isEndOfLine(c));
        return res.toString();
    }

    public double readDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, readInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, readInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }
    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }
    public boolean isSpaceChar(int c)
    {
        if (filter != null)
            return filter.isSpaceChar(c);
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public String next()
    {
        return readString();
    }

    public interface SpaceCharFilter
    {
        public boolean isSpaceChar(int ch);
    }
    public boolean isEndOfLine(int c) {
        return c == '\n' || c == '\r' || c == -1;
    }
}

//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	//StringBuilder sb=new StringBuilder("");
	 //InputReader in = new InputReader(System.in);
	//PrintWriter pw=new PrintWriter(System.out);
	//String line=br.readLine().trim();

	//int t=Integer.parseInt(br.readLine());
  //	while(t-->0)
  	//{
  	//int n=Integer.parseInt(br.readLine());
	//long n=Long.parseLong(br.readLine());
	//String l[]=br.readLine().split(" ");
  //int m=Integer.parseInt(l[0]);
	//int k=Integer.parseInt(l[1]);
	//String l[]=br.readLine().split(" ");
	//l=br.readLine().split(" ");
	/*int a[]=new int[n];
	for(int i=0;i<n;i++)
	{
		a[i]=Integer.parseInt(l[i]);
	}*/
	   //System.out.println(" ");

	//}
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;

import java.io.IOException;
import java.io.PrintWriter;

public class C_383 {
	public static int mod = 1000000007;
	static FastReader scan = new FastReader();
	static PrintWriter out = new PrintWriter(System.out);

	public static void main(String args[]) {
		/******************* code ***********************/
		int n = scan.nextInt();
		int arr[] = scan.nextIntArray(n);
		ArrayList<Pair> A = new ArrayList<>();
		int index = 0;
		int sum = 0;
		int l = 0;
		int r = 0;
		for (int i = 0; i < n; i++) {
			r = i;
			sum = sum + arr[i];
			index = index + i + 1;
			if (sum == index) {
				A.add(new Pair(l, r));
				l = r + 1;
				sum = 0;
				index = 0;
			}
		}
		if (A.size() == 0) {
			out.println(-1);
		} else {
			int diff = -1;
			int flag = 0;
			for (Pair p : A) {
				if (diff == -1) {
					diff = p.y - p.x + 1;
					if (diff % 2 == 0)
						diff = diff / 2;
				} else {
					int temp = (p.y - p.x + 1);
					if (temp % 2 == 0)
						temp = temp / 2;
					if (temp > diff) {
						diff = p.y - p.x;
						flag = 1;
					}
				}
			}
			out.println(diff);
		}
		out.close();

	}

	static class Pair implements Comparable<Pair> {
		int x;
		int y;

		Pair(int xx, int yy) {
			x = xx;
			y = yy;
		}

		@Override
		public int compareTo(Pair o) {
			if (Long.compare(this.y, o.y) != 0)
				return Integer.compare(this.y, o.y);
			else
				return Long.compare(this.x, o.x);
		}
	}

	public static void debug(Object... o) {
		System.out.println(Arrays.deepToString(o));
	}

	public static long pow(long x, long n, long mod) {
		long res = 1;
		x %= mod;
		while (n > 0) {
			if (n % 2 == 1) {
				res = (res * x) % mod;
			}
			x = (x * x) % mod;
			n /= 2;
		}
		return res;
	}

	/************** Scanner ********************/
	static class FastReader {
		private byte[] buf = new byte[1024];
		private int curChar;
		private int snumChars;

		public int read() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = System.in.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public String nextLine() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public long nextLong() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		public long[] nextLongArray(int n) {
			long[] arr = new long[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLong();
			}
			return arr;
		}

		private boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

	}

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Rustam Musin (PloadyFree@gmail.com)
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        private int n;
        private int[] call;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            n = in.readInt();
            call = IOUtils.readIntArray(in, n);
            MiscUtils.decreaseByOne(call);
            out.print(solve());
        }

        private int solve() {
            int[] lasts = new int[n];
            for (int i = 0; i < n; i++) {
                lasts[i] = i;
            }
            outer:
            for (int t = 1; t < 1e6; t++) {
                for (int i = 0; i < n; i++) {
                    lasts[i] = call[lasts[i]];
                }
                for (int i = 0; i < n; i++) {
                    if (lasts[lasts[i]] != i) {
                        continue outer;
                    }
                }
                return t;
            }
            return -1;
        }

    }

    static class MiscUtils {
        public static void decreaseByOne(int[]... arrays) {
            for (int[] array : arrays) {
                for (int i = 0; i < array.length; i++) {
                    array[i]--;
                }
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void print(int i) {
            writer.print(i);
        }

    }

    static class IOUtils {
        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.readInt();
            }
            return array;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        int n;
        int[] next;
        int[] colors;
        int[] parent;
        List<Integer> sizes;
        boolean[] inCycle;

        public void solve(int testNumber, InputReader in, PrintWriter out) {

            n = in.nextInt();
            next = new int[n];
            sizes = new ArrayList<>();
            parent = new int[n];
            inCycle = new boolean[n];
            colors = new int[n];
            for (int i = 0; i < n; i++) {
                next[i] = in.nextInt() - 1;
                colors[i] = -1;
            }
            for (int i = 0; i < n; i++) {
                if (colors[i] == -1) {
                    parent[i] = -1;
                    dfs(i);
                }
            }
            for (int i = 0; i < n; i++) {
                if (!inCycle[i]) {
                    out.println(-1);
                    return;
                }
            }
            long gcd = 1;
            long p = 1;
            for (int size : sizes) {
                if (size % 2 == 0)
                    size /= 2;
                gcd = gcd(gcd, size);
                p *= size;
            }
            out.println(p / gcd);
        }

        private long gcd(long a, long b) {
            return (b == 0) ? a : gcd(b, a % b);
        }

        private void dfs(int v) {
            colors[v] = 0;
            if (colors[next[v]] == 0) {
                cycle(v, next[v]);
            } else {
                parent[next[v]] = v;
                dfs(next[v]);
            }
            colors[v] = 1;
        }

        private void cycle(int v, int root) {
            int cur = v;
            int l = 1;
            inCycle[cur] = true;
            while (cur != root) {
                l++;
                cur = parent[cur];
                inCycle[cur] = true;
            }
            sizes.add(l);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class cfs383C {

	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int N = sc.nextInt();
		int[] c = new int[N];
		for (int n = 0; n < N; n++)
		{
			c[n] = sc.nextInt() - 1;
		}
		Set<Integer> v = new HashSet<Integer>();
		ArrayList<Integer> clist = new ArrayList<Integer>();
		loop:
		for (int n = 0; n < N; n++)
		{
			if (!v.contains(n))	//unvisited
			{
				int s = n;
				int size = 0;
				int i = n;
				do {
					v.add(i);
					int j = c[i];
					size++;
					if (v.contains(j))
					{
						if (j == s) //found beginning of cycle
						{
							clist.add(size % 2 == 0 ? size / 2 : size);
							continue loop;
						}
						else
						{
							System.out.println(-1);
							System.exit(0);
						}
					}
					i = j;
				} while (true);
			}
		}
		long lcm = 1;
		for (int i = 0; i < clist.size(); i++)
		{
			lcm = lcm(lcm, clist.get(i));
		}
		System.out.println(lcm);

	}
	public static long lcm (long a, long b)
	{
		//find gcd
		long gcd = 1;
		for (int i = 2; i < Math.min(a, b); i++)
		{
			if (a % i == 0 && b % i == 0)
				gcd = i;

		}
		return  a * b / gcd;

	}
	public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }

        public FastScanner() {
            this(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }

        long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextLong();
            }
            return a;
        }
    }

}

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Objects;
import java.util.StringTokenizer;

public final class Main {
    static char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    static char[] chars1 = {'#', '*', '&'};
    static char[] chars2 = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};

    static boolean oneColor = true;

    // x1<0
    // x1+k*2>0;
    // k*2>-x1;
    // k=-x1/2
    public void solve() {
        int n = in.nextInt();
        int[] crush = new int[100];
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
            for (int j=0;j<i;j++){
                if (crush[j]==crush[i]){
                    out.println(-1);
                    return;
                }
            }
        }
        ArrayList<Integer> al = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int tmp = crush[i];
            int t = 1;
            while (tmp != i) {
                tmp = crush[tmp];
                t++;
            }
            if (t % 2 == 0) {
                al.add(t / 2);
            } else {
                al.add(t);
            }
        }
        long lcm = al.get(0);
        for (int i=1; i<al.size();i++){
            lcm=Library.lcm(lcm,al.get(0));
        }
        out.println(lcm);
    }

    static class Library {
        static boolean isPrime(int a) {
            if (a == 1) {
                return false;
            }
            for (int i = 2; i * i <= a; i++) {
                if (a % i == 0)
                    return false;
            }
            return true;
        }

        static long bpow(long x, long n, long m) {
            long count = 1;
            if (n == 0) {
                return 1;
            }
            while (n > 0) {
                if ((n & 1) == 1) {
                    count *= x;
                    count %= m;
                }
                x *= x;
                x %= m;
                n >>= 1;
            }
            return count % m;
        }

        static long GCD(long a, long b) {
            if (b == 0) return a;
            return GCD(b, a % b);
        }

        static long lcm(long a, long b) {
            return (a * b) / Library.GCD(a, b);
        }
    }

    class Pair<X, Y> implements Comparable<Pair<X, Y>> {

        public X first;
        public Y second;

        public Pair(X first, Y second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public int hashCode() {
            int hash = 7;
            hash = 11 * hash + Objects.hashCode(this.first);
            hash = 11 * hash + Objects.hashCode(this.second);
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Pair<?, ?> other = (Pair<?, ?>) obj;
            if (!Objects.equals(this.first, other.first)) {
                return false;
            }
            if (!Objects.equals(this.second, other.second)) {
                return false;
            }
            return true;
        }

        @Override
        public int compareTo(Pair<X, Y> p) {
            return ((Comparable<X>) first).compareTo(p.first);
        }

        @Override
        public String toString() {
            return first + " " + second;
        }
    }

    class Node<E> {
        E element;
        Node<E> next;
        Node<E> prev;

        Node(E element, Node next, Node prev) {
            this.element = element;
            this.next = next;
            this.prev = prev;
        }
    }

    //    -------------I/O-------------    \\
    private FScanner in;

    private PrintWriter out;

    public static void main(String[] args) {
        new Main().runIO();
    }

    void run() {
        try {
            in = new FScanner(new File("input.txt"));
            out = new PrintWriter(new BufferedWriter(new FileWriter(new File("output.txt"))));
            solve();
            out.close();
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    void runIO() {
        in = new FScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out));
        solve();
        out.close();
        in.close();
    }

    class FScanner {

        private BufferedReader br;
        private StringTokenizer st;

        public FScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
        }

        void useString(String s) {
            if (s != null) {
                st = new StringTokenizer(s);
            }
        }

        void updateST() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String next() {
            updateST();
            return st.nextToken();
        }

        Long[] nextLongArray() {
            updateST();
            LinkedList<Long> ll = new LinkedList<>();
            while (st.hasMoreElements()) {
                ll.add(Long.parseLong(st.nextToken()));
            }
            Long[] arr = new Long[1];
            return ll.toArray(arr);
        }

        Integer[] nextIntArray() {
            updateST();
            LinkedList<Integer> ll = new LinkedList<>();
            while (st.hasMoreElements()) {
                ll.add(Integer.parseInt(st.nextToken()));
            }
            Integer[] arr = new Integer[1];
            return ll.toArray(arr);
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            updateST();
            StringBuilder sb = new StringBuilder(st.nextToken());
            while (st.hasMoreElements()) {
                sb.append(st.nextToken());
            }
            return sb.toString();
        }

        void close() {
            try {
                br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.LinkedList;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            HashSet<Integer>[] arr = new HashSet[n + 1];
            for (int i = 1; i <= n; i++)
                arr[i] = new HashSet<>();
            for (int i = 1; i <= n; i++) {
                int temp = in.nextInt();
                arr[i].add(temp);
                arr[temp].add(temp);
            }
            for (int i = 1; i <= n; i++) {
                if (arr[i].size() == 1 && arr[i].contains(i))
                    continue;
                else if (arr[i].size() != 2) {
                    out.println(-1);
                    return;
                }
            }
            boolean[] visited = new boolean[n + 1];
            int max = 1;
            for (int i = 1; i <= n; i++) {
                if (!visited[i]) {
                    int count = 1;
                    LinkedList<Integer> queue = new LinkedList<>();
                    queue.add(i);
                    visited[i] = true;
                    while (queue.size() != 0) {
                        int temp = queue.removeFirst();
                        Iterator<Integer> iterator = arr[temp].iterator();
                        while (iterator.hasNext()) {
                            int next = iterator.next();
                            if (!visited[next]) {
                                count++;
                                visited[next] = true;
                                queue.add(next);
                            }
                        }
                    }
                    if (count == 2)
                        count = 1;
                    max = lcm(count, max);
                }
            }
            out.println(max);
        }

        static int lcm(int a, int b) {
            int tmep = a * b;
            return tmep / gcd(a, b);
        }

        static int gcd(int a, int b) {
            if (b == 0)
                return a;
            return gcd(b, a % b);
        }

    }

    static class InputReader {
        BufferedReader br;
        StringTokenizer st;

        public InputReader(InputStream inputStream) {
            br = new BufferedReader(new InputStreamReader(inputStream));
        }

        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    throw new RuntimeException();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.util.Scanner;

public class Crush {

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int a[] = new int[n];
		for(int i=0;i<n;i++)
		{
			a[i] = sc.nextInt();
		}

		int mint=-1;
		int t=-1;
		for(int i=0;i<n;i++)
		{
			if(i+1==a[i])
				continue;
			else
			{
				int count=0;
				int f[] = new int[n];
				int j=i;
				while(true)
				{

					if(j==a[j]-1)
						break;
					if(a[j]-1==i)
					{
						if(count>1)
							t=++count;
						else
							t=count;
						break;
					}
					if(f[j] > 0)
					{
						break;
					}
					f[j]=1;
					j=a[j]-1;
					count++;
				}
				if(mint==-1)
					mint=t;
				else if(t<mint)
					mint=t;
			}
		}
		System.out.println(mint);
	}

}

import java.util.*;
import java.io.*;

public class ggg {

	private static InputStream stream;
	private static byte[] buf = new byte[1024];
	private static int curChar;
	private static int numChars;
	private static SpaceCharFilter filter;
	private static PrintWriter pw;

	private static void soln(){
		int n=nextInt();
		int[] arr=new int[n];
		for(int i=0;i<n;i++)
			arr[i]=nextInt();
		int lcm=1;
		int flag=0;
		for(int i=0;i<n;i++){
			int[] visited=new int[n];
			int k=arr[i];
			visited[i]=1;
			int t=1;
			while(k!=(i+1)){
				t++;
				if(k==arr[k-1] || visited[k-1]==1){
					flag=1;
					t=1;
					break;
				}
				visited[k-1]=1;
				k=arr[k-1];
			}
			if(t%2==0)
				t=t/2;
			//System.out.println(t+" "+(i+1));
			lcm=lcm(lcm,t);
		}
		if(flag!=1)
			pw.println(lcm);
		else
			pw.println(-1);
	}
	private static int gcd(int a,int b){
		if(b==0)
			return a;
		else return gcd(b,a%b);
	}
	private static int lcm(int a,int b){
		return (a*b)/gcd(a,b);
	}
	private static int min(int a,int b){
		if(a>b)
			return b;
		else
			return a;
	}
	private static class Pair implements Comparable<Pair>{
		int x;
		int y;
		public Pair(int a,int b){
			x=a;
			y=b;
		}
		@Override
		public int compareTo(Pair arg0) {
			if(this.x > arg0.x)
				return 1;
			return 0;
		}
	}
	static long pow(int a, long b, int MOD) {
		long x = 1, y = a;
		    while(b > 0) {
		        if(b%2 == 1) {
		            x=(x*y);
		            if(x>MOD) x%=MOD;
		        }
		        y = (y*y);
		        if(y>MOD) y%=MOD;
		        b /= 2;
		    }
		    return x;
		}

		static long modInverse(int a,long b, int m) {
			//pw.println((m-2)*b);
		    return pow(a,(m-2)*b,m);
		}
	private static void computeLpsArray(String pat,int size,int[] lps){
		int len=0;
		int i=1;
		lps[0]=0;
		while(i<size){
			if(pat.charAt(i)==pat.charAt(len)){
				len++;
				lps[i]=len;
				i++;
			}else{
				if(len!=0){
					len=lps[len-1];
				}else{
					lps[i]=len;
					i++;
				}
			}
		}
	}
	private static int KMP(String pat,String txt){
		int m=pat.length();
		int n=txt.length();
		int[] lps=new int[m];
		int j=0;
		int len=0;
		int index=0;
		computeLpsArray(pat,m,lps);
		int i=0;
		while(i<n){
			if(pat.charAt(j)==txt.charAt(i)){
				i++;
				j++;
			}else{
				if(j!=0)
					j=lps[j-1];
				else
					i++;
			}
			if(len<j){
				len=j;
				//pw.println(i);
				index=i;
			}
		}
		return index-len;
	}
	private static int max(int a,int b){
		if(a>b)
			return a;
		return b;
	}
	public static void main(String[] args) {
		InputReader(System.in);
		pw = new PrintWriter(System.out);
		soln();
		pw.close();
	}

	// To Get Input
	// Some Buffer Methods

	public static void InputReader(InputStream stream1) {
		stream = stream1;
	}

	private static boolean isWhitespace(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private static boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}

	private static int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	private static int nextInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	private static long nextLong() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	private static String nextToken() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	private static String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	private static int[] nextIntArray(int n) {
		int[] arr = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = nextInt();
		}
		return arr;
	}

	private static long[] nextLongArray(int n) {
		long[] arr = new long[n];
		for (int i = 0; i < n; i++) {
			arr[i] = nextLong();
		}
		return arr;
	}

	private static void pArray(int[] arr) {
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
		return;
	}

	private static void pArray(long[] arr) {
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
		return;
	}

	private static boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return isWhitespace(c);
	}

	private interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Random;
import java.util.StringTokenizer;

public class A {
    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
        FastScanner sc = new FastScanner();

        int n = sc.nextInt();
        int[] crush = new int[n];
        for (int i = 0; i < n; i++) {
            crush[i] = sc.nextInt() - 1;
        }

        outer:
        for (int t = 1; t <= n; t++) {
            for (int x = 0; x < n; x++) {
                int y = get(t, x, crush);
                int xx = get(t, y, crush);
                if (x != xx) {
                    continue outer;
                }
            }
            System.out.println(t);
            return;
        }

        System.out.println(-1);
    }

    static int get(int t, int cur, int[] crush) {
        if (t == 0) {
            return cur;
        }
        return get(t - 1, crush[cur], crush);
    }

    static void shuffle(int[] arr) {
        Random rng = new Random();
        int length = arr.length;
        for (int idx = 0; idx < arr.length; idx++) {
            int toSwap = idx + rng.nextInt(length-idx);
            int tmp = arr[idx];
            arr[idx] = arr[toSwap];
            arr[toSwap] = tmp;
        }
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;
        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }
        public FastScanner() {
            this(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }
        long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextLong();
            }
            return a;
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int N = in.nextInt();
            int[] next = new int[N];
            for (int i = 0; i < N; i++) {
                next[i] = in.nextInt() - 1;
            }
            int[] match = new int[N];
            for (int i = 0; i < N; i++) {
                match[i] = i;
            }
            iter:
            for (int t = 1; t <= 100000; t++) {
                for (int j = 0; j < N; j++) {
                    match[j] = next[match[j]];
                }
                for (int j = 0; j < N; j++) {
                    if (j != match[match[j]]) {
                        continue iter;
                    }
                }
                out.println(t);
                return;
            }
            out.println(-1);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.util.Scanner;

public class Crush {

	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int a[] = new int[n];
		for(int i=0;i<n;i++)
		{
			a[i] = sc.nextInt();
		}

		int mint=-1;
		int t=-1;
		for(int i=0;i<n;i++)
		{
			if(i+1==a[i])
				continue;
			else
			{
				int count=0;
				int f[] = new int[n];
				int j=i;
				while(true)
				{

					if(j==a[j]-1)
						break;
					if(a[j]-1==i)
					{
						if(count>1)
							t=++count;
						else
							t=count;
						break;
					}
					if(f[j] > 0)
					{
						t=-1;
						break;
					}
					f[j]=1;
					j=a[j]-1;
					count++;
				}
				if(mint==-1)
					mint=t;
				else if(t<mint)
					mint=t;
			}
		}
		System.out.println(mint);
	}

}

//package Div383;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by YSingh on 24/12/16.
 */
public class ProblemC {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());
        String line2 = sc.nextLine();
        String[] numbers = line2.split(" ");
        int [] arr = new int[n + 1];

        for (int i = 0; i < numbers.length; i++) {
            arr[i + 1] = Integer.parseInt(numbers[i]);
        }

        int min = Integer.MAX_VALUE;
        int val = 0;

        for(int i = 1; i <= n; i++) {
            val = getCycleLength(i, i, arr);
            if(val > 0 && val < min) {
                min = val;
            }
        }

        System.out.println(min == Integer.MAX_VALUE ? -1 : min);
    }

    private static int getCycleLength(int source, int i, int[] arr) {
        if(arr[i] == source) {
            return 0;
        }
        else if(arr[i] == i) {
            return - arr.length;
        }
        return 1 + getCycleLength(source, arr[i], arr);
    }
}

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by Shahjahan on 4/29/2017.
 * http://codeforces.com/contest/742/problem/C
 */
public class C {
    public static void main(String[] args) throws IOException {
        // BufferedReader br = new BufferedReader(new FileReader("F:\\Acm\\src\\input.txt"));
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int crush[] = new int[n + 1];

        String[] parts = br.readLine().split(" ");
        for (int i = 1; i <= n; i++) {
            crush[i] = Integer.parseInt(parts[i - 1]);
        }

        int t;
        for (t = 1; t <= n; t++) {
            boolean conditionSatisfy = true;
            for (int x = 1; x <= n; x++) {
                int person = x;
                if (person == crush[person]) continue;

                for (int count = 1; count <= t; count++) {
                    person = crush[person];
                }

                for (int count = 1; count <= t; count++) {
                    person = crush[person];
                }

                if (person != x) {
                    conditionSatisfy = false;
                    break;
                }
            }

            if (conditionSatisfy) {
                break;
            }
        }
        if (t > n)
            System.out.println(-1);
        else
            System.out.println(t);
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Mayur Kulkarni
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        BladeReader in = new BladeReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, BladeReader in, PrintWriter out) {
            int s = in.nextInt();
            int[] arr = new int[s];
            for (int i = 0; i < s; i++) {
                arr[i] = in.nextInt() - 1;
            }
            for (int t = 1; t <= arr.length + 1; t++) {
                boolean[] covered = new boolean[arr.length];
                int[] end = new int[arr.length];
                for (int i = 0; i < arr.length; i++) {
                    int steps = 0;
                    int curr = i;
                    while (steps < t) {
                        curr = arr[curr];
                        steps++;
                    }
                    end[i] = curr;
                }
                for (int i = 0; i < arr.length; i++) {
                    if (end[end[i]] == i) {
                        covered[i] = true;
                        covered[end[i]] = true;
                    }
                }
                int ans = 0;
                for (int i = 0; i < covered.length; i++) {
                    if (covered[i]) ans++;
                }
                if (ans == covered.length) {
                    out.println(t);
                    return;
                }
            }
            out.println(-1);
        }
    }

    static class BladeReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public BladeReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

import java.util.*;
import java.io.*;
import java.awt.geom.*;
import java.math.*;

public class C {

	static final Scanner in = new Scanner(System.in);
	static final PrintWriter out = new PrintWriter(System.out,false);
	static boolean debug = false;

	static boolean[] visited;
	static int n;
	static int[] a;

	static int rec(int cur) {
		if (visited[cur]) return 0;
		visited[cur] = true;
		return rec(a[cur]) + 1;
	}

	static long gcd(long a, long b) {
		if (a == 0) return b;
		return gcd(b%a, a);
	}

	static void solve() {
		n = in.nextInt();
		a = new int[n];
		boolean[] f = new boolean[n];
		for (int i=0; i<n; i++) {
			a[i] = in.nextInt() - 1;
			if (f[a[i]]) {
				out.println("-1");
				return;
			}
			f[a[i]] = true;
		}
		visited = new boolean[n];
		long ans = 1;
		for (int i=0; i<n; i++) {
			if (!visited[i]) {
				int tmp = rec(i);
				tmp = tmp == 2 ? 1 : tmp;
				ans = ans*tmp / gcd(ans, tmp);
			}
		}

		out.println(ans);
	}

	public static void main(String[] args) {
		debug = args.length > 0;
		long start = System.nanoTime();

		solve();
		out.flush();

		long end = System.nanoTime();
		dump((end - start) / 1000000 + " ms");
		in.close();
		out.close();
	}

	static void dump(Object... o) { if (debug) System.err.println(Arrays.deepToString(o)); }
}

import java.io.IOException;
import java.util.Scanner;

public class R383C
{
	static int[] arr;
	public static void main(String[] args) throws IOException
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		arr = new int[n];
		for (int i = 0; i < arr.length; i++)
		{
			arr[i] = sc.nextInt();
		}

		for (int i = 1; i < arr.length+5; i++)
		{
			if(check(i))
			{
				System.out.println(i);
				return;
			}
		}
		System.out.println(-1);

	}
	private static boolean check(int t)
	{
		int[] target = new int[arr.length];

		for (int i = 0; i < arr.length; i++)
		{
			if(target[i] == 0)
			{
				int tt = i;
				for (int j = 0; j < t; j++)
				{
					tt = arr[tt]-1;
				}
				target[i] = tt;
			}

			int crush = target[i];
			if(target[crush] == 0)
			{
				int tt = crush;
				for (int j = 0; j < t; j++)
				{
					tt = arr[tt]-1;
				}
				target[crush] = tt;
			}

			if(target[crush] != i)
				return false;
		}

		return true;
	}
}

import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.text.DecimalFormat;

public class C {
	static int[] nxt = new int[105];
	static boolean[] vis = new boolean[105];
	static int len[] = new int[105];
	static int k = 0;
	static int gcd(int a,int b)
	{
	    int temp;
	    while(b!=0)
	    {
	        temp = b;
	        b = a % b;
	        a = temp;
	    }
	    return a;
	}
	static int lcm(int a,int b){
		return a*b/gcd(a,b);
	}
	static boolean iscircle(int x){
		if(x==nxt[x]) return true;
		int a= nxt[x];
		int l = 1;
		while(a!=x){
			a = nxt[a];
			l++;
			if(l>=105) return false;
		}
		len[k++] = l;
		return true;
	}
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		for(int i = 1;i<=n;i++){
			int j = scan.nextInt();
			nxt[i] = j;
		}
		for(int i = 1;i<=n;i++){
			if(!iscircle(i)){
				System.out.println(-1);
				return;
			}
		}
		int ans = 1;
		for(int i = 0;i<k;i++){
			if(len[i]%2==0)ans = lcm(ans,len[i]/2);
			else ans = lcm(ans,len[i]);
		}
		System.out.println(ans);
	}
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.StringTokenizer;

/**
 *
 * @author Public
 */
public class A741 {
    static int count=0;
     public static void main(String[] args) throws Exception{
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer(br.readLine());
        int n=Integer.parseInt(st.nextToken());

     LinkedList ad[]=new LinkedList[n];

   boolean visited[]=new boolean[n];
   Arrays.fill(visited,false);
   StringTokenizer st1=new StringTokenizer(br.readLine());
     for(int i=0;i<n;i++){
     ad[i]=new LinkedList();
     int k=Integer.parseInt(st1.nextToken());
     if(k-1!=i)
     ad[i].add(k-1);
     }
         int t=0;

   class dfs{
  void DFS(int x,boolean[] v){
      count++;
  v[x]=true;
  ListIterator itr= ad[x].listIterator();
  while(itr.hasNext()){
  int n=(int)itr.next();
   if(v[n]==false)
          DFS(n,v);
  }
  }
 }

     for(int i=0;i<n;i++){
      count=0;

  if(visited[i]==false){
     new dfs().DFS(i,visited);
         if((ad[count+i-1].isEmpty()) ){
             if(count==1)
             t=Math.max(t,1);
             else{ System.out.println(-1);
    return;    }}
         else if(count==2 && (int)ad[count+i-1].getFirst()==i) {t=Math.max(t,1);}
   else if((ad[count+i-1].isEmpty() && count!=1) ||((int)ad[count+i-1].getFirst()!=i)){
         System.out.println(-1);
    return;
   }
   else {
   t=Math.max(t,count);
   }
  }
         }

     System.out.println(t);
     }
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class C {

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);
		int n = Integer.parseInt(br.readLine());
		int[] a = new int[n];
		String[] split = br.readLine().split(" ");
		for(int i = 0; i < n; i++) a[i] = Integer.parseInt(split[i])-1;
		int min = Integer.MAX_VALUE;
		for(int i = 1; i <= 10000; i++){
			if(test(i, a)){
				min = i;
				break;
			}
		}
		System.out.println(min == Integer.MAX_VALUE?-1:min);
	}

	static boolean test(int time, int[] a){
		for(int i = 0; i < a.length; i++){
			int x = search(i, a, time);
			int y = search(x, a, time);
			if(i != y) return false;
		}
		return true;
	}

	static int search(int idx, int[] a, int time){
		if(time == 0) return idx;
		return search(a[idx], a, time-1);
	}

}

//package baobab;

import java.io.*;
import java.util.*;

public class C {

    public static void main(String[] args) {
        Solver solver = new Solver();
    }

    static class Solver {
        IO io;

        public Solver() {
            this.io = new IO();
            try {
                solve();
            } finally {
                io.close();
            }
        }

        /****************************** START READING HERE ********************************/

        void solve() {
            int n = io.nextInt();
            int[] crush = new int[n+1];
            for (int i=1; i<=n; i++) {
                crush[i] = io.nextInt();
            }
            HashSet<Integer> possibles = new HashSet<>();
            for (int start=1; start<=n; start++) {
                int t = 0;
                int curr = start;
                boolean[] vis = new boolean[n+1];
                while (!vis[curr]) {
                    vis[curr] = true;
                    curr = crush[curr];
                    t++;
                }
                if (curr != start) {
                    io.println(-1);
                    return;
                }
                if (t%2 == 0) {
                    t /= 2;
                }
                possibles.add(t);
            }

            for (int i=1; i<=1000000; i++) {
                if (possible4all(possibles, i)) {
                    io.println(i);
                    return;
                }
            }

            io.println(-1);
        }

        boolean possible4all(HashSet<Integer> possibles, int i) {
            for (Integer p : possibles) {
                if (i % p != 0) return false;
            }
            return true;
        }

        /************************** UTILITY CODE BELOW THIS LINE **************************/

        long MOD = (long)1e9 + 7;

        List<Integer>[] toGraph(IO io, int n) {
            List<Integer>[] g = new ArrayList[n+1];
            for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
            for (int i=1; i<=n-1; i++) {
                int a = io.nextInt();
                int b = io.nextInt();
                g[a].add(b);
                g[b].add(a);
            }
            return g;
        }

        class Point {
            int y;
            int x;

            public Point(int y, int x) {
                this.y = y;
                this.x = x;
            }
        }

        class IDval implements Comparable<IDval> {
            int id;
            long val;

            public IDval(int id, long val) {
                this.val = val;
                this.id = id;
            }

            @Override
            public int compareTo(IDval o) {
                if (this.val < o.val) return -1;
                if (this.val > o.val) return 1;
                return this.id - o.id;
            }
        }

        long pow(long base, int exp) {
            if (exp == 0) return 1L;
            long x = pow(base, exp/2);
            long ans = x * x;
            if (exp % 2 != 0) ans *= base;
            return ans;
        }

        class ElementCounter {
            private HashMap<Long, Long> elements;

            public ElementCounter() {
                elements = new HashMap<>();
            }

            public void add(long element) {
                long count = 1;
                if (elements.containsKey(element)) count += elements.get(element);
                elements.put(element, count);
            }

            public void remove(long element) {
                long count = elements.get(element);
                count--;
                if (count == 0) elements.remove(element);
                else elements.put(element, count);
            }

            public long get(long element) {
                if (!elements.containsKey(element)) return 0;
                return elements.get(element);
            }

            public int size() {
                return elements.size();
            }
        }

        class StringCounter {
            HashMap<String, Long> elements;

            public StringCounter() {
                elements = new HashMap<>();
            }

            public void add(String identifier) {
                long count = 1;
                if (elements.containsKey(identifier)) count += elements.get(identifier);
                elements.put(identifier, count);
            }

            public void remove(String identifier) {
                long count = elements.get(identifier);
                count--;
                if (count == 0) elements.remove(identifier);
                else elements.put(identifier, count);
            }

            public long get(String identifier) {
                if (!elements.containsKey(identifier)) return 0;
                return elements.get(identifier);
            }

            public int size() {
                return elements.size();
            }
        }

        class LCAFinder {

            /* O(n log n) Initialize: new LCAFinder(graph)
             * O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */

            int[] nodes;
            int[] depths;
            int[] entries;
            int pointer;
            FenwickMin fenwick;

            public LCAFinder(List<Integer>[] graph) {
                this.nodes = new int[(int)10e6];
                this.depths = new int[(int)10e6];
                this.entries = new int[graph.length];
                this.pointer = 1;
                boolean[] visited = new boolean[graph.length+1];
                dfs(1, 0, graph, visited);
                fenwick = new FenwickMin(pointer-1);
                for (int i=1; i<pointer; i++) {
                    fenwick.set(i, depths[i] * 1000000L + i);
                }
            }

            private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
                visited[node] = true;
                entries[node] = pointer;
                nodes[pointer] = node;
                depths[pointer] = depth;
                pointer++;
                for (int neighbor : graph[node]) {
                    if (visited[neighbor]) continue;
                    dfs(neighbor, depth+1, graph, visited);
                    nodes[pointer] = node;
                    depths[pointer] = depth;
                    pointer++;
                }
            }

            public int find(int a, int b) {
                int left = entries[a];
                int right = entries[b];
                if (left > right) {
                    int temp = left;
                    left = right;
                    right = temp;
                }
                long mixedBag = fenwick.getMin(left, right);
                int index = (int) (mixedBag % 1000000L);
                return nodes[index];
            }
        }

        class FenwickMin {
            long n;
            long[] original;
            long[] bottomUp;
            long[] topDown;

            public FenwickMin(int n) {
                this.n = n;
                original = new long[n+2];
                bottomUp = new long[n+2];
                topDown = new long[n+2];
            }

            public void set(int modifiedNode, long value) {
                long replaced = original[modifiedNode];
                original[modifiedNode] = value;
                // Update left tree
                int i = modifiedNode;
                long v = value;
                while (i <= n) {
                    if (v > bottomUp[i]) {
                        if (replaced == bottomUp[i]) {
                            v = Math.min(v, original[i]);
                            for (int r=1 ;; r++) {
                                int x = (i&-i)>>>r;
                                if (x == 0) break;
                                int child = i-x;
                                v = Math.min(v, bottomUp[child]);
                            }
                        } else break;
                    }
                    if (v == bottomUp[i]) break;
                    bottomUp[i] = v;
                    i += (i&-i);
                }
                // Update right tree
                i = modifiedNode;
                v = value;
                while (i > 0) {
                    if (v > topDown[i]) {
                        if (replaced == topDown[i]) {
                            v = Math.min(v, original[i]);
                            for (int r=1 ;; r++) {
                                int x = (i&-i)>>>r;
                                if (x == 0) break;
                                int child = i+x;
                                if (child > n+1) break;
                                v = Math.min(v, topDown[child]);
                            }
                        } else break;
                    }
                    if (v == topDown[i]) break;
                    topDown[i] = v;
                    i -= (i&-i);
                }
            }

            public long getMin(int a, int b) {
                long min = original[a];
                int prev = a;
                int curr = prev + (prev&-prev); // parent right hand side
                while (curr <= b) {
                    min = Math.min(min, topDown[prev]); // value from the other tree
                    prev = curr;
                    curr = prev + (prev&-prev);;
                }
                min = Math.min(min, original[prev]);
                prev = b;
                curr = prev - (prev&-prev); // parent left hand side
                while (curr >= a) {
                    min = Math.min(min,bottomUp[prev]); // value from the other tree
                    prev = curr;
                    curr = prev - (prev&-prev);
                }
                return min;
            }

        }

        class FenwickSum {
            public long[] d;

            public FenwickSum(int n) {
                d=new long[n+1];
            }

            /** a[0] must be unused. */
            public FenwickSum(long[] a) {
                d=new long[a.length];
                for (int i=1; i<a.length; i++) {
                    modify(i, a[i]);
                }
            }

            /** Do not modify i=0. */
            void modify(int i, long v) {
                while (i<d.length) {
                    d[i] += v;
                    // Move to next uplink on the RIGHT side of i
                    i += (i&-i);
                }
            }

            /** Returns sum from a to b, *BOTH* inclusive. */
            long getSum(int a, int b) {
                return getSum(b) - getSum(a-1);
            }

            private long getSum(int i) {
                long sum = 0;
                while (i>0) {
                    sum += d[i];
                    // Move to next uplink on the LEFT side of i
                    i -= (i&-i);
                }
                return sum;
            }
        }

        class SegmentTree {
            /** Query sums with log(n) modifyRange */
            int N;
            long[] p;

            public SegmentTree(int n) {
                /* TODO: Test that this works. */
                N = n;
                p = new long[2*N];
            }

            public void modifyRange(int a, int b, long change) {
                muuta(a, change);
                muuta(b+1, -change);
            }

            void muuta(int k, long muutos) {
                k += N;
                p[k] += muutos;
                for (k /= 2; k >= 1; k /= 2) {
                    p[k] = p[2*k] + p[2*k+1];
                }
            }

            public long get(int k) {
                int a = N;
                int b = k+N;
                long s = 0;
                while (a <= b) {
                    if (a%2 == 1) s += p[a++];
                    if (b%2 == 0) s += p[b--];
                    a /= 2;
                    b /= 2;
                }
                return s;
            }

        }

        class Zalgo {

            public int pisinEsiintyma(String haku, String kohde) {
                char[] s = new char[haku.length() + 1 + kohde.length()];
                for (int i=0; i<haku.length(); i++) {
                    s[i] = haku.charAt(i);
                }
                int j = haku.length();
                s[j++] = '#';
                for (int i=0; i<kohde.length(); i++) {
                    s[j++] = kohde.charAt(i);
                }
                int[] z = toZarray(s);
                int max = 0;
                for (int i=haku.length(); i<z.length; i++) {
                    max = Math.max(max, z[i]);
                }
                return max;
            }

            public int[] toZarray(char[] s) {
                int n = s.length;
                int[] z = new int[n];
                int a = 0, b = 0;
                for (int i = 1; i < n; i++) {
                    if (i > b) {
                        for (int j = i; j < n && s[j - i] == s[j]; j++)  z[i]++;
                    }
                    else {
                        z[i] = z[i - a];
                        if (i + z[i - a] > b) {
                            for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
                            a = i;
                            b = i + z[i] - 1;
                        }
                    }
                }
                return z;
            }

            public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
                // this is alternative use case
                char[] s = new char[haku.length() + 1 + kohde.length()];
                for (int i=0; i<haku.length(); i++) {
                    s[i] = haku.charAt(i);
                }
                int j = haku.length();
                s[j++] = '#';
                for (int i=0; i<kohde.length(); i++) {
                    s[j++] = kohde.charAt(i);
                }
                int[] z = toZarray(s);
                List<Integer> indexes = new ArrayList<>();
                for (int i=haku.length(); i<z.length; i++) {
                    if (z[i] < haku.length()) continue;
                    indexes.add(i);
                }
                return indexes;
            }

        }

        class StringHasher {

            class HashedString {
                long[] hashes;
                long[] modifiers;

                public HashedString(long[] hashes, long[] modifiers) {
                    this.hashes = hashes;
                    this.modifiers = modifiers;
                }
            }

            long P;
            long M;

            public StringHasher() {
                initializePandM();
            }

            HashedString hashString(String s) {
                int n = s.length();
                long[] hashes = new long[n];
                long[] modifiers = new long[n];
                hashes[0] = s.charAt(0);
                modifiers[0] = 1;
                for (int i=1; i<n; i++) {
                    hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
                    modifiers[i] = (modifiers[i-1] * P) % M;
                }
                return new HashedString(hashes, modifiers);
            }

            /**
             * Indices are inclusive.
             */
            long getHash(HashedString hashedString, int startIndex, int endIndex) {
                long[] hashes = hashedString.hashes;
                long[] modifiers = hashedString.modifiers;
                long result = hashes[endIndex];
                if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
                if (result < 0) result += M;
                return result;
            }

            // Less interesting methods below

            /**
             * Efficient for 2 input parameter strings in particular.
             */
            HashedString[] hashString(String first, String second) {
                HashedString[] array = new HashedString[2];
                int n = first.length();
                long[] modifiers = new long[n];
                modifiers[0] = 1;

                long[] firstHashes = new long[n];
                firstHashes[0] = first.charAt(0);
                array[0] = new HashedString(firstHashes, modifiers);

                long[] secondHashes = new long[n];
                secondHashes[0] = second.charAt(0);
                array[1] = new HashedString(secondHashes, modifiers);

                for (int i=1; i<n; i++) {
                    modifiers[i] = (modifiers[i-1] * P) % M;
                    firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
                    secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
                }
                return array;
            }

            /**
             * Efficient for 3+ strings
             * More efficient than multiple hashString calls IF strings are same length.
             */
            HashedString[] hashString(String... strings) {
                HashedString[] array = new HashedString[strings.length];
                int n = strings[0].length();
                long[] modifiers = new long[n];
                modifiers[0] = 1;
                for (int j=0; j<strings.length; j++) {
                    // if all strings are not same length, defer work to another method
                    if (strings[j].length() != n) {
                        for (int i=0; i<n; i++) {
                            array[i] = hashString(strings[i]);
                        }
                        return array;
                    }

                    // otherwise initialize stuff
                    long[] hashes = new long[n];
                    hashes[0] = strings[j].charAt(0);
                    array[j] = new HashedString(hashes, modifiers);
                }
                for (int i=1; i<n; i++) {
                    modifiers[i] = (modifiers[i-1] * P) % M;
                    for (int j=0; j<strings.length; j++) {
                        String s = strings[j];
                        long[] hashes = array[j].hashes;
                        hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
                    }
                }
                return array;
            }

            void initializePandM() {
                ArrayList<Long> modOptions = new ArrayList<>(20);
                modOptions.add(353873237L);
                modOptions.add(353875897L);
                modOptions.add(353878703L);
                modOptions.add(353882671L);
                modOptions.add(353885303L);
                modOptions.add(353888377L);
                modOptions.add(353893457L);
                P = modOptions.get(new Random().nextInt(modOptions.size()));

                modOptions.clear();
                modOptions.add(452940277L);
                modOptions.add(452947687L);
                modOptions.add(464478431L);
                modOptions.add(468098221L);
                modOptions.add(470374601L);
                modOptions.add(472879717L);
                modOptions.add(472881973L);
                M = modOptions.get(new Random().nextInt(modOptions.size()));

            }
        }

        private static class Prob {

            /** For heavy calculations on probabilities, this class
             *  provides more accuracy & efficiency than doubles.
             *  Math explained: https://en.wikipedia.org/wiki/Log_probability
             *  Quick start:
             *      - Instantiate probabilities, eg. Prob a = new Prob(0.75)
             *      - add(), multiply() return new objects, can perform on nulls & NaNs.
             *      - get() returns probability as a readable double */

            /** Logarithmized probability. Note: 0% represented by logP NaN. */
            private double logP;

            /** Construct instance with real probability. */
            public Prob(double real) {
                if (real > 0) this.logP = Math.log(real);
                else this.logP = Double.NaN;
            }

            /** Construct instance with already logarithmized value. */
            static boolean dontLogAgain = true;
            public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
                this.logP = logP;
            }

            /** Returns real probability as a double. */
            public double get() {
                return Math.exp(logP);
            }

            @Override
            public String toString() {
                return ""+get();
            }

            /***************** STATIC METHODS BELOW ********************/

            /** Note: returns NaN only when a && b are both NaN/null. */
            public static Prob add(Prob a, Prob b) {
                if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
                if (nullOrNaN(a)) return copy(b);
                if (nullOrNaN(b)) return copy(a);

                double x = a.logP;
                double y = b.logP;
                double sum = x + Math.log(1 + Math.exp(y - x));
                return new Prob(sum, dontLogAgain);
            }

            /** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
            public static Prob multiply(Prob a, Prob b) {
                if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
                return new Prob(a.logP + b.logP, dontLogAgain);
            }

            /** Returns true if p is null or NaN. */
            private static boolean nullOrNaN(Prob p) {
                return (p == null || Double.isNaN(p.logP));
            }

            /** Returns a new instance with the same value as original. */
            private static Prob copy(Prob original) {
                return new Prob(original.logP, dontLogAgain);
            }
        }

        public class StronglyConnectedComponents {

            /** Kosaraju's algorithm */

            ArrayList<Integer>[] forw;
            ArrayList<Integer>[] bacw;

            /** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */
            public int getCount(int n, int[] mista, int[] minne) {
                forw = new ArrayList[n+1];
                bacw = new ArrayList[n+1];
                for (int i=1; i<=n; i++) {
                    forw[i] = new ArrayList<Integer>();
                    bacw[i] = new ArrayList<Integer>();
                }
                for (int i=0; i<mista.length; i++) {
                    int a = mista[i];
                    int b = minne[i];
                    forw[a].add(b);
                    bacw[b].add(a);
                }
                int count = 0;
                List<Integer> list = new ArrayList<Integer>();
                boolean[] visited = new boolean[n+1];
                for (int i=1; i<=n; i++) {
                    dfsForward(i, visited, list);
                }
                visited = new boolean[n+1];
                for (int i=n-1; i>=0; i--) {
                    int node = list.get(i);
                    if (visited[node]) continue;
                    count++;
                    dfsBackward(node, visited);
                }
                return count;
            }

            public void dfsForward(int i, boolean[] visited, List<Integer> list) {
                if (visited[i]) return;
                visited[i] = true;
                for (int neighbor : forw[i]) {
                    dfsForward(neighbor, visited, list);
                }
                list.add(i);
            }

            public void dfsBackward(int i, boolean[] visited) {
                if (visited[i]) return;
                visited[i] = true;
                for (int neighbor : bacw[i]) {
                    dfsBackward(neighbor, visited);
                }
            }
        }

        class DrawGrid {

            void draw(boolean[][] d) {
                System.out.print("  ");
                for (int x=0; x<d[0].length; x++) {
                    System.out.print(" " + x + " ");
                }
                System.out.println("");
                for (int y=0; y<d.length; y++) {
                    System.out.print(y + " ");
                    for (int x=0; x<d[0].length; x++) {
                        System.out.print((d[y][x] ? "[x]" : "[ ]"));
                    }
                    System.out.println("");
                }
            }

            void draw(int[][] d) {
                int max = 1;
                for (int y=0; y<d.length; y++) {
                    for (int x=0; x<d[0].length; x++) {
                        max = Math.max(max, ("" + d[y][x]).length());
                    }
                }
                System.out.print("  ");
                String format = "%" + (max+2) + "s";
                for (int x=0; x<d[0].length; x++) {
                    System.out.print(String.format(format, x) + " ");
                }
                format = "%" + (max) + "s";
                System.out.println("");
                for (int y=0; y<d.length; y++) {
                    System.out.print(y + " ");
                    for (int x=0; x<d[0].length; x++) {
                        System.out.print(" [" + String.format(format, (d[y][x])) + "]");
                    }
                    System.out.println("");
                }
            }

        }

        class BaseConverter {

            /* Palauttaa luvun esityksen kannassa base */
            public String convert(Long number, int base) {
                return Long.toString(number, base);
            }

            /* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */
            public String convert(String number, int baseFrom, int baseTo) {
                return Long.toString(Long.parseLong(number, baseFrom), baseTo);
            }

            /* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
            public long longify(String number, int baseFrom) {
                return Long.parseLong(number, baseFrom);
            }
        }

        class Binary implements Comparable<Binary> {

            /**
             * Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
             *
             * When manipulating small binary strings, instantiate new Binary(string)
             * When just reading large binary strings, instantiate new Binary(string,true)
             * get(int i) returns a character '1' or '0', not an int.
             */

            private boolean[] d;
            private int first; // Starting from left, the first (most remarkable) '1'
            public int length;

            public Binary(String binaryString) {
                this(binaryString, false);
            }
            public Binary(String binaryString, boolean initWithMinArraySize) {
                length = binaryString.length();
                int size = Math.max(2*length, 1);
                first = length/4;
                if (initWithMinArraySize) {
                    first = 0;
                    size = Math.max(length, 1);
                }
                d = new boolean[size];
                for (int i=0; i<length; i++) {
                    if (binaryString.charAt(i) == '1') d[i+first] = true;
                }
            }

            public void addFirst(char c) {
                if (first-1 < 0) doubleArraySize();
                first--;
                d[first] = (c == '1' ? true : false);
                length++;
            }

            public void addLast(char c) {
                if (first+length >= d.length) doubleArraySize();
                d[first+length] = (c == '1' ? true : false);
                length++;
            }

            private void doubleArraySize() {
                boolean[] bigArray = new boolean[(d.length+1) * 2];
                int newFirst = bigArray.length / 4;
                for (int i=0; i<length; i++) {
                    bigArray[i + newFirst] = d[i + first];
                }
                first = newFirst;
                d = bigArray;
            }

            public boolean flip(int i) {
                boolean value = (this.d[first+i] ? false : true);
                this.d[first+i] = value;
                return value;
            }

            public void set(int i, char c) {
                boolean value = (c == '1' ? true : false);
                this.d[first+i] = value;
            }

            public char get(int i) {
                return (this.d[first+i] ? '1' : '0');
            }

            @Override
            public int compareTo(Binary o) {
                if (this.length != o.length) return this.length - o.length;
                int len = this.length;
                for (int i=0; i<len; i++) {
                    int diff = this.get(i) - o.get(i);
                    if (diff != 0) return diff;
                }
                return 0;
            }

            @Override
            public String toString() {
                StringBuilder sb = new StringBuilder();
                for (int i=0; i<length; i++) {
                    sb.append(d[i+first] ? '1' : '0');
                }
                return sb.toString();
            }

        }

        class BinomialCoefficients {
            /** Total number of K sized unique combinations from pool of size N (unordered)
             N! / ( K! (N - K)! )   */

            /** For simple queries where output fits in long. */
            public long biCo(long n, long k) {
                long r = 1;
                if (k > n) return 0;
                for (long d = 1; d <= k; d++) {
                    r *= n--;
                    r /= d;
                }
                return r;
            }

            /** For multiple queries with same n, different k. */
            public long[] precalcBinomialCoefficientsK(int n, int maxK) {
                long v[] = new long[maxK+1];
                v[0] = 1; // nC0 == 1
                for (int i=1; i<=n; i++) {
                    for (int j=Math.min(i,maxK); j>0; j--) {
                        v[j] = v[j] + v[j-1]; // Pascal's triangle
                    }
                }
                return v;
            }

            /** When output needs % MOD. */
            public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
                long v[] = new long[k+1];
                v[0] = 1; // nC0 == 1
                for (int i=1; i<=n; i++) {
                    for (int j=Math.min(i,k); j>0; j--) {
                        v[j] = v[j] + v[j-1]; // Pascal's triangle
                        v[j] %= M;
                    }
                }
                return v;
            }
        }

        class GreatestCommonDivisor {

            /** Chained calls to Euclidean algorithm. */
            long gcd(long... v) {
                if (v.length == 1) return v[0];
                long ans = gcd(v[1], v[0]);
                for (int i=2; i<v.length; i++) {
                    ans = gcd(ans, v[i]);
                }
                return ans;
            }

            /** Euclidean algorithm. */
            long gcd(long a, long b) {
                if (b == 0) return a;
                return gcd(b, a%b);
            }
        }

        private class IO extends PrintWriter {
            private InputStreamReader r;
            private static final int BUFSIZE = 1 << 15;
            private char[] buf;
            private int bufc;
            private int bufi;
            private StringBuilder sb;

            public IO() {
                super(new BufferedOutputStream(System.out));
                r = new InputStreamReader(System.in);

                buf = new char[BUFSIZE];
                bufc = 0;
                bufi = 0;
                sb = new StringBuilder();
            }

            private void fillBuf() throws IOException {
                bufi = 0;
                bufc = 0;
                while(bufc == 0) {
                    bufc = r.read(buf, 0, BUFSIZE);
                    if(bufc == -1) {
                        bufc = 0;
                        return;
                    }
                }
            }

            private boolean pumpBuf() throws IOException {
                if(bufi == bufc) {
                    fillBuf();
                }
                return bufc != 0;
            }

            private boolean isDelimiter(char c) {
                return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
            }

            private void eatDelimiters() throws IOException {
                while(true) {
                    if(bufi == bufc) {
                        fillBuf();
                        if(bufc == 0) throw new RuntimeException("IO: Out of input.");
                    }

                    if(!isDelimiter(buf[bufi])) break;
                    ++bufi;
                }
            }

            public String next() {
                try {
                    sb.setLength(0);

                    eatDelimiters();
                    int start = bufi;

                    while(true) {
                        if(bufi == bufc) {
                            sb.append(buf, start, bufi - start);
                            fillBuf();
                            start = 0;
                            if(bufc == 0) break;
                        }

                        if(isDelimiter(buf[bufi])) break;
                        ++bufi;
                    }

                    sb.append(buf, start, bufi - start);

                    return sb.toString();
                } catch(IOException e) {
                    throw new RuntimeException("IO.next: Caught IOException.");
                }
            }

            public int nextInt() {
                try {
                    int ret = 0;

                    eatDelimiters();

                    boolean positive = true;
                    if(buf[bufi] == '-') {
                        ++bufi;
                        if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
                        positive = false;
                    }

                    boolean first = true;
                    while(true) {
                        if(!pumpBuf()) break;
                        if(isDelimiter(buf[bufi])) {
                            if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
                            break;
                        }
                        first = false;

                        if(buf[bufi] >= '0' && buf[bufi] <= '9') {
                            if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
                            ret *= 10;
                            ret -= (int)(buf[bufi] - '0');
                            if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
                        } else {
                            throw new RuntimeException("IO.nextInt: Invalid int.");
                        }

                        ++bufi;
                    }

                    if(positive) {
                        if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
                        ret = -ret;
                    }

                    return ret;
                } catch(IOException e) {
                    throw new RuntimeException("IO.nextInt: Caught IOException.");
                }
            }

            public long nextLong() {
                try {
                    long ret = 0;

                    eatDelimiters();

                    boolean positive = true;
                    if(buf[bufi] == '-') {
                        ++bufi;
                        if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
                        positive = false;
                    }

                    boolean first = true;
                    while(true) {
                        if(!pumpBuf()) break;
                        if(isDelimiter(buf[bufi])) {
                            if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
                            break;
                        }
                        first = false;

                        if(buf[bufi] >= '0' && buf[bufi] <= '9') {
                            if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
                            ret *= 10;
                            ret -= (long)(buf[bufi] - '0');
                            if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
                        } else {
                            throw new RuntimeException("IO.nextLong: Invalid long.");
                        }

                        ++bufi;
                    }

                    if(positive) {
                        if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
                        ret = -ret;
                    }

                    return ret;
                } catch(IOException e) {
                    throw new RuntimeException("IO.nextLong: Caught IOException.");
                }
            }

            public double nextDouble() {
                return Double.parseDouble(next());
            }

        }
    }

}

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class C implements Closeable {

    private InputReader in = new InputReader(System.in);
    private PrintWriter out = new PrintWriter(System.out);

    public void solve() {
        int n = in.ni();
        int[] x = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            x[i] = in.ni();
        }
        int max = -1;
        out: for (int i = 1; i <= n; i++) {
            boolean[] visited = new boolean[n + 1];
            int current = i;
            int t = 0;
            while (!visited[current]) {
                visited[current] = true;
                t++;
                if (current == x[current]) continue out;
                current = x[current];
            }
            if (t == 2) t--;
            if (t >= 1 && t > max) {
                max = t;
            }
        }
        out.println(max >= 1 ? max : -1);
    }

    @Override
    public void close() throws IOException {
        in.close();
        out.close();
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int ni() {
            return Integer.parseInt(next());
        }

        public long nl() {
            return Long.parseLong(next());
        }

        public void close() throws IOException {
            reader.close();
        }
    }

    public static void main(String[] args) throws IOException {
        try (C instance = new C()) {
            instance.solve();
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Rustam Musin (PloadyFree@gmail.com)
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        private int n;
        private int[] call;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            n = in.readInt();
            call = IOUtils.readIntArray(in, n);
            MiscUtils.decreaseByOne(call);
            out.print(solve());
        }

        private int solve() {
            int[][] finishes = new int[n][(int) 2e3];
            for (int start = 0; start < n; start++) {
                for (int time = 0; time < finishes[0].length; time++) {
                    int finish = start;
                    int time0 = time;
                    while (time0-- > 0) {
                        finish = call[finish];
                    }
                    finishes[start][time] = finish;
                }
            }

            outer:
            for (int time = 1; time < finishes[0].length; time++) {
                for (int start = 0; start < n; start++) {
                    int finish = finishes[start][time];
                    if (finishes[finish][time] != start) {
                        continue outer;
                    }
                }
                return time;
            }

            return -1;
        }

    }

    static class MiscUtils {
        public static void decreaseByOne(int[]... arrays) {
            for (int[] array : arrays) {
                for (int i = 0; i < array.length; i++) {
                    array[i]--;
                }
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void print(int i) {
            writer.print(i);
        }

    }

    static class IOUtils {
        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.readInt();
            }
            return array;
        }

    }
}

/*package com.fancita.codeforces;*/

import java.io.*;
import java.util.InputMismatchException;

/**
 * Created by ashutosh on 6/12/16.
 */
public class c383 extends FastIO {
    public static void main(String[] args) {
        int n = reader.readInt();
        int[] arr = new int[n+1];
        IOUtils.readIntArray(reader, arr, 1);
        run(arr, n);
        writer.flush();
        writer.close();
    }

    public static void run(int[] arr, int maxIndex) {
        int ret = Integer.MIN_VALUE;
        boolean[] visited = new boolean[maxIndex+1];
        for (int i = 1; i <= maxIndex; i++) {
            if (!visited[i]) {
                visited[i] = true;
                int start = i;
                int present = arr[i];
                int count = 1;
                while (start != present) {
                    if (visited[present]) {
                        count = Integer.MIN_VALUE;
                        break;
                    }
                    count++;
                    visited[present] = true;
                    present = arr[present];
                }
                ret = Integer.max(ret, count % 2 == 0 ? count / 2 : count);
            }
        }
        writer.print(ret < 0 ? -1 : ret);
    }
}

class FastIO {

    public static InputReader reader = new InputReader(System.in);
    public static OutputWriter writer	=	new OutputWriter(System.out);

    public static class InputReader {

        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }

    public static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0)
                    writer.print(' ');
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

        public void flush() {
            writer.flush();
        }

    }

    public static class IOUtils {

        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++)
                array[i] = in.readInt();
            return array;
        }

        /**
         * Read items into array starting from a given point
         * @param in
         * @param arr
         * @param i is starting point
         */
        public static void readIntArray(InputReader in, int[] arr, int i) {
            int n = arr.length;
            for (int j = i; j < n; j++) {
                arr[j] = in.readInt();
            }
        }
    }
}

import java.io.*;
import java.util.LinkedList;
import java.util.Objects;
import java.util.StringTokenizer;

public final class Main {
    static char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    static char[] chars1 = {'#', '*', '&'};
    static char[] chars2 = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};

    static boolean oneColor = true;

    // x1<0
    // x1+k*2>0;
    // k*2>-x1;
    // k=-x1/2
    public void solve() {
        int n = in.nextInt();
        int[] crush = new int[100];
        int tmax = 100*150;
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
            if (crush[i] == i) {
                tmax--;
            }
        }
        int t = 1;
        while (t <= tmax) {
            boolean b = true;
            for (int x = 0; x < n; x++) {
                b = false;
                int z = t;
                int y = x;
                while (z >= 1) {
                    y = crush[y];
                    z--;
                }
                z = t;
                int tmp = y;
                while (z >= 1) {
                    y = crush[y];
                    z--;
                }
                if (y == x) {
                    b = true;
                }
                if (!b) {
                    break;
                }
            }
            if (b) {
                out.println(t);
                return;
            }
            t++;
        }
        out.println(-1);
    }

    static class Library {
        static boolean isPrime(int a) {
            if (a == 1) {
                return false;
            }
            for (int i = 2; i * i <= a; i++) {
                if (a % i == 0)
                    return false;
            }
            return true;
        }

        static long bpow(long x, long n, long m) {
            long count = 1;
            if (n == 0) {
                return 1;
            }
            while (n > 0) {
                if ((n & 1) == 1) {
                    count *= x;
                    count %= m;
                }
                x *= x;
                x %= m;
                n >>= 1;
            }
            return count % m;
        }

        static long GCD(long a, long b) {
            if (b == 0) return a;
            return GCD(b, a % b);
        }
    }

    class Pair<X, Y> implements Comparable<Pair<X, Y>> {

        public X first;
        public Y second;

        public Pair(X first, Y second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public int hashCode() {
            int hash = 7;
            hash = 11 * hash + Objects.hashCode(this.first);
            hash = 11 * hash + Objects.hashCode(this.second);
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Pair<?, ?> other = (Pair<?, ?>) obj;
            if (!Objects.equals(this.first, other.first)) {
                return false;
            }
            if (!Objects.equals(this.second, other.second)) {
                return false;
            }
            return true;
        }

        @Override
        public int compareTo(Pair<X, Y> p) {
            return ((Comparable<X>) first).compareTo(p.first);
        }

        @Override
        public String toString() {
            return first + " " + second;
        }
    }

    class Node<E> {
        E element;
        Node<E> next;
        Node<E> prev;

        Node(E element, Node next, Node prev) {
            this.element = element;
            this.next = next;
            this.prev = prev;
        }
    }

    //    -------------I/O-------------    \\
    private FScanner in;

    private PrintWriter out;

    public static void main(String[] args) {
        new Main().runIO();
    }

    void run() {
        try {
            in = new FScanner(new File("input.txt"));
            out = new PrintWriter(new BufferedWriter(new FileWriter(new File("output.txt"))));
            solve();
            out.close();
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    void runIO() {
        in = new FScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out));
        solve();
        out.close();
        in.close();
    }

    class FScanner {

        private BufferedReader br;
        private StringTokenizer st;

        public FScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
        }

        void useString(String s) {
            if (s != null) {
                st = new StringTokenizer(s);
            }
        }

        void updateST() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String next() {
            updateST();
            return st.nextToken();
        }

        Long[] nextLongArray() {
            updateST();
            LinkedList<Long> ll = new LinkedList<>();
            while (st.hasMoreElements()) {
                ll.add(Long.parseLong(st.nextToken()));
            }
            Long[] arr = new Long[1];
            return ll.toArray(arr);
        }

        Integer[] nextIntArray() {
            updateST();
            LinkedList<Integer> ll = new LinkedList<>();
            while (st.hasMoreElements()) {
                ll.add(Integer.parseInt(st.nextToken()));
            }
            Integer[] arr = new Integer[1];
            return ll.toArray(arr);
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            updateST();
            StringBuilder sb = new StringBuilder(st.nextToken());
            while (st.hasMoreElements()) {
                sb.append(st.nextToken());
            }
            return sb.toString();
        }

        void close() {
            try {
                br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.readInt();
            int[] a = IOUtils.readIntArray(in, n);
            MiscUtils.decreaseByOne(a);
            int[] cnt = new int[n];
            for (int x : a) cnt[x]++;
            for (int x : cnt)
                if (x != 1) {
                    out.printLine(-1);
                    return;
                }

            TreeSet<Integer> set = new TreeSet<>();
            for (int i = 0; i < n; i++) {
                int x = i;
                int len = 0;
                while (true) {
                    x = a[x];
                    len++;
                    if (x == i) break;
                }
                set.add(len);
            }

            for (int ans : set) {
                if (ans % 2 == 0) {
                    boolean ok = true;
                    for (int x : set) {
                        if (ans == x) continue;
                        if ((ans / 2) % x != 0) {
                            ok = false;
                        }
                    }
                    if (ok) {
                        out.printLine(ans / 2);
                        return;
                    }
                }

                {
                    boolean ok = true;
                    for (int x : set) {
                        if (ans == x) continue;
                        if (ans % x != 0) {
                            ok = false;
                        }
                    }
                    if (ok) {
                        out.printLine(ans);
                        return;
                    }
                }
            }

            out.printLine(-1);
        }

    }

    static class MiscUtils {
        public static void decreaseByOne(int[]... arrays) {
            for (int[] array : arrays) {
                for (int i = 0; i < array.length; i++) {
                    array[i]--;
                }
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void printLine(int i) {
            writer.println(i);
        }

    }

    static class IOUtils {
        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.readInt();
            }
            return array;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.LinkedList;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            HashSet<Integer>[] arr = new HashSet[n + 1];
            for (int i = 1; i <= n; i++)
                arr[i] = new HashSet<>();
            for (int i = 1; i <= n; i++) {
                int temp = in.nextInt();
                arr[i].add(temp);
                arr[temp].add(temp);
            }
            for (int i = 1; i <= n; i++) {
                if (arr[i].size() == 1 && arr[i].contains(i))
                    continue;
                else if (arr[i].size() != 2) {
                    out.println(-1);
                    return;
                }
            }
            boolean[] visited = new boolean[n + 1];
            int max = 1;
            for (int i = 1; i <= n; i++) {
                if (!visited[i]) {
                    int count = 1;
                    LinkedList<Integer> queue = new LinkedList<>();
                    queue.add(i);
                    visited[i] = true;
                    while (queue.size() != 0) {
                        int temp = queue.removeFirst();
                        Iterator<Integer> iterator = arr[temp].iterator();
                        while (iterator.hasNext()) {
                            int next = iterator.next();
                            if (!visited[next]) {
                                count++;
                                visited[next] = true;
                                queue.add(next);
                            }
                        }
                    }
                    if (count == 2)
                        count = 1;
                    max = lcm(count, max);
                }
            }
            out.println(max);
        }

        static int lcm(int a, int b) {
            int tmep = a * b;
            return tmep / gcd(a, b);
        }

        static int gcd(int a, int b) {
            if (b == 0)
                return a;
            return gcd(b, a % b);
        }

    }

    static class InputReader {
        BufferedReader br;
        StringTokenizer st;

        public InputReader(InputStream inputStream) {
            br = new BufferedReader(new InputStreamReader(inputStream));
        }

        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    throw new RuntimeException();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.*;    //PrintWriter
import java.math.*;  //BigInteger, BigDecimal
import java.util.*;  //StringTokenizer, ArrayList

public class R383_Div2_C
{
	FastReader in;
	PrintWriter out;

	public static void main(String[] args)  {
		new R383_Div2_C().run();
	}

	void run()
	{
		in = new FastReader(System.in);
		out = new PrintWriter(System.out);
		solve();
		out.close();
	}

	void solve()
	{
		int n = in.nextInt();

		int[] a = new int[n+1];
		boolean[] used = new boolean[n+1];
		for (int i = 1; i <= n; i++)
			a[i] = in.nextInt();

		ArrayList<Integer> cycle = new ArrayList<>();
		int max = 0;
		long lcm = 1;
		for (int i = 1; i <= n; i++)
			if (!used[i])
			{
				used[i] = true;
				int cyc = 1;
				int nex = a[i];
				while (!used[nex])
				{
					used[nex] = true;
					nex = a[nex];
					cyc++;
				}
				if (i != nex)
				{
					lcm = -1;
					break;
				}
				cycle.add(cyc);
				if (cyc % 2 == 0) cyc /= 2;
				max = Math.max(max, cyc);
				lcm = LCM(max, lcm);
			}

		out.println(lcm);
	}

    long GCD(long a, long b)
    {
        if (b == 0) return a;
        return GCD(b, a % b);
    }
    long LCM(long a, long b)
    {
        return a * b / GCD(a, b);
    }

	//-----------------------------------------------------
	void runWithFiles() {
		in = new FastReader(new File("input.txt"));
		try {
			out = new PrintWriter(new File("output.txt"));
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		solve();
		out.close();
	}

	class FastReader
	{
	    BufferedReader br;
	    StringTokenizer tokenizer;

	    public FastReader(InputStream stream)
	    {
	        br = new BufferedReader(new InputStreamReader(stream));
	        tokenizer = null;
	    }
		public FastReader(File f) {
			try {
				br = new BufferedReader(new FileReader(f));
				tokenizer = null;
			}
			catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

	    private String next() {
	        while (tokenizer == null || !tokenizer.hasMoreTokens())
	            try {
	            	tokenizer = new StringTokenizer(br.readLine());
	            }
	            catch (IOException e) {
	                throw new RuntimeException(e);
	            }
	        return tokenizer.nextToken();
	    }
		public String nextLine() {
			try	{
				return br.readLine();
			}
			catch(Exception e) {
				throw(new RuntimeException());
			}
		}

	    int nextInt() {
	        return Integer.parseInt(next());
	    }
	    long nextLong() {
	        return Long.parseLong(next());
	    }
	    double nextDouble() {
	        return Double.parseDouble(next());
	    }
	    BigInteger nextBigInteger() {
	        return new BigInteger(next());
	    }
	    BigDecimal nextBigDecimal() {
	        return new BigDecimal(next());
	    }
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Rustam Musin (PloadyFree@gmail.com)
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        private int n;
        private int[] call;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            n = in.readInt();
            call = IOUtils.readIntArray(in, n);
            MiscUtils.decreaseByOne(call);
            out.print(solve());
        }

        private int solve() {
            int[] lasts = new int[n];
            for (int i = 0; i < n; i++) {
                lasts[i] = i;
            }
            outer:
            for (int t = 1; t < 1e5; t++) {
                for (int i = 0; i < n; i++) {
                    lasts[i] = call[lasts[i]];
                }
                for (int i = 0; i < n; i++) {
                    if (lasts[lasts[i]] != i) {
                        continue outer;
                    }
                }
                return t;
            }
            return -1;
        }

    }

    static class MiscUtils {
        public static void decreaseByOne(int[]... arrays) {
            for (int[] array : arrays) {
                for (int i = 0; i < array.length; i++) {
                    array[i]--;
                }
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void print(int i) {
            writer.print(i);
        }

    }

    static class IOUtils {
        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.readInt();
            }
            return array;
        }

    }
}

import java.io.*;
import java.util.*;

public final class Main {
    static char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    static char[] chars1 = {'#', '*', '&'};
    static char[] chars2 = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};

    static boolean oneColor = true;

    // x1<0
    // x1+k*2>0;
    // k*2>-x1;
    // k=-x1/2
    public void solve() {
        int n = in.nextInt();
        int[] crush = new int[100];
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
        }
        TreeSet<Integer> al = new TreeSet<>();
        for (int i=0;i<n;i++){
            int tmp = crush[i];
            int t=1;
            while (tmp!=i && t<=n){
                int tmpp=tmp;
                tmp=crush[tmp];
                if (tmpp==tmp){
                    out.println(-1);
                    return;
                }
                t++;
            }
            if (t>n) {
                out.println(-1);
                return;
            }
            if (t%2 ==0) {
                al.add(t/2);
            }else {
                al.add(t);
            }
        }
        long gcd =al.first();
        for (int i:al){
                gcd=Library.GCD(gcd,i);
        }
        long pra = 1;
        for(int i:al){
            pra*=i;
        }
        out.println(pra/gcd);
    }

    static class Library {
        static boolean isPrime(int a) {
            if (a == 1) {
                return false;
            }
            for (int i = 2; i * i <= a; i++) {
                if (a % i == 0)
                    return false;
            }
            return true;
        }

        static long bpow(long x, long n, long m) {
            long count = 1;
            if (n == 0) {
                return 1;
            }
            while (n > 0) {
                if ((n & 1) == 1) {
                    count *= x;
                    count %= m;
                }
                x *= x;
                x %= m;
                n >>= 1;
            }
            return count % m;
        }

        static long GCD(long a, long b) {
            if (b == 0) return a;
            return GCD(b, a % b);
        }
    }

    class Pair<X, Y> implements Comparable<Pair<X, Y>> {

        public X first;
        public Y second;

        public Pair(X first, Y second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public int hashCode() {
            int hash = 7;
            hash = 11 * hash + Objects.hashCode(this.first);
            hash = 11 * hash + Objects.hashCode(this.second);
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Pair<?, ?> other = (Pair<?, ?>) obj;
            if (!Objects.equals(this.first, other.first)) {
                return false;
            }
            if (!Objects.equals(this.second, other.second)) {
                return false;
            }
            return true;
        }

        @Override
        public int compareTo(Pair<X, Y> p) {
            return ((Comparable<X>) first).compareTo(p.first);
        }

        @Override
        public String toString() {
            return first + " " + second;
        }
    }

    class Node<E> {
        E element;
        Node<E> next;
        Node<E> prev;

        Node(E element, Node next, Node prev) {
            this.element = element;
            this.next = next;
            this.prev = prev;
        }
    }

    //    -------------I/O-------------    \\
    private FScanner in;

    private PrintWriter out;

    public static void main(String[] args) {
        new Main().runIO();
    }

    void run() {
        try {
            in = new FScanner(new File("input.txt"));
            out = new PrintWriter(new BufferedWriter(new FileWriter(new File("output.txt"))));
            solve();
            out.close();
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    void runIO() {
        in = new FScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out));
        solve();
        out.close();
        in.close();
    }

    class FScanner {

        private BufferedReader br;
        private StringTokenizer st;

        public FScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
        }

        void useString(String s) {
            if (s != null) {
                st = new StringTokenizer(s);
            }
        }

        void updateST() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String next() {
            updateST();
            return st.nextToken();
        }

        Long[] nextLongArray() {
            updateST();
            LinkedList<Long> ll = new LinkedList<>();
            while (st.hasMoreElements()) {
                ll.add(Long.parseLong(st.nextToken()));
            }
            Long[] arr = new Long[1];
            return ll.toArray(arr);
        }

        Integer[] nextIntArray() {
            updateST();
            LinkedList<Integer> ll = new LinkedList<>();
            while (st.hasMoreElements()) {
                ll.add(Integer.parseInt(st.nextToken()));
            }
            Integer[] arr = new Integer[1];
            return ll.toArray(arr);
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            updateST();
            StringBuilder sb = new StringBuilder(st.nextToken());
            while (st.hasMoreElements()) {
                sb.append(st.nextToken());
            }
            return sb.toString();
        }

        void close() {
            try {
                br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

import java.io.*;
import java.util.*;
import java.math.*;
public class StronglyConnectedComponent
{
	BufferedReader in;
	PrintWriter ob;
	StringTokenizer st;
	static ArrayList<Integer> gr[];
	static ArrayList<Integer> transpose[];
	static int n;
	public static void main(String[] args) throws IOException {
		new StronglyConnectedComponent().run();
	}
	void run() throws IOException {
		//in=new BufferedReader(new FileReader("input.txt"));
		in=new BufferedReader(new InputStreamReader(System.in));
		ob=new PrintWriter(System.out);
		solve();
		ob.flush();
	}
	@SuppressWarnings("unchecked")
	void solve() throws IOException {
		n=ni();
		gr=new ArrayList[n+1];
		transpose=new ArrayList[n+1];
		for (int i=0; i<=n ;  i++ )
			{
				gr[i]=new ArrayList<Integer>();
				transpose[i]=new ArrayList<Integer>();
			}
		for (int i=1; i<=n ; i++ ) {
			int v=ni();
			gr[i].add(v);
			transpose[v].add(i);
		}
		SSCs obj=new SSCs();
		Set<Integer> s=obj.printSSC();
		//ob.println(s);
		int f=0;
		long ans=1;
		int k=0;
		for(int i : s) {
			k=i;
			if(i!=1) f=1;
			if(i==2)
				ans*=1;
			else
				ans=ans*1L*i;
		}
		if(s.size()==1 && k!=1)
			ob.println(k==2?1:k);
		else
		ob.println(f==0?"-1":ans);
	}
	int ni() throws IOException {
		return Integer.parseInt(nextToken());
	}
	String nextToken() throws IOException {
		if(st==null || !st.hasMoreTokens())
			st=new StringTokenizer(in.readLine());
		return st.nextToken();
	}
}
class SSCs extends StronglyConnectedComponent {
	Stack<Integer> stk=new Stack<Integer>();
	boolean visited[];
	Set printSSC() {
		visited=new boolean[n+1];
		for(int i=1;i<=n;i++) {
			if(!visited[i]) {
				dfs(i);
			}
		}
		Arrays.fill(visited,false);
		//System.out.println("The Strongly Connected Components Are : ");\
		Set<Integer> set=new TreeSet<Integer>();
		while(!stk.isEmpty()) {
			int pop=stk.pop();
			if(visited[pop]==false) {
				int cnt=dfsutil(pop);
				//System.out.println(cnt);
				set.add(cnt);
			}
		}
		return set;
	}
	void dfs(int u) {
		visited[u]=true;
		for(int v : gr[u]) {
			if(!visited[v])
				{
					dfs(v);
				}
		}
		stk.push(u);
	}
	int dfsutil(int u) {
		visited[u]=true;
		//System.out.print(u+" ");
		for(int v : transpose[u])
			{
				if(!visited[v])
					return 1+dfsutil(v);
			}
		return 1;
	}
}

import java.util.Scanner;

public class ArpasLoudOwf {
	static int n;
	static int crush[];
	static boolean vis[];
	public static int getCycle(int curNode,int index,int step)
	{
		if (index==curNode && step!=0)
			return step;
		if (vis[curNode])
			return -1;
		vis[curNode] = true;
		int res = getCycle(crush[curNode], index, step+1);
		vis[curNode] = false;
		return res;
	}
	public static int lcm(int a,int b)
	{
		return a*b/gcd(a,b);
	}
	public static int gcd(int a,int b)
	{
		return b == 0 ? a : gcd(b, a % b);
	}
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		crush = new int[n];
		vis = new boolean[n];
		for (int i=0;i<n;i++)
			crush[i] = sc.nextInt()-1;
		int lcm = 1;
		for (int i=0;i<n;i++)
		{
			int x = getCycle(i,i,0);
			if (x==-1)
			{
				System.out.println(x);
				return;
			}
//			System.out.println(x);
			if (x%2==0)
				x/=2;
			lcm = lcm(lcm,x);
		}
		System.out.println(lcm);
	}
}

import java.util.*;
import java.io.*;

/**
 *
 * @author umang
 */

public class C741 {

    public static int mod = 1000000007;
    public static int[] dp;
    public static int t;

    public static void dfs(int[] a,int x,boolean[] visited,int n){
        visited[x]=true;
        t++;
        if(a[x]==n){
            dp[n]=t;
            return;
        }
        if(!visited[a[x]])
            dfs(a,a[x],visited,n);
    }

    public static void main(String[] args) {

        InputReader in = new InputReader(System.in);
        PrintWriter w = new PrintWriter(System.out);

        int n=in.nextInt();
        dp=new int[n];
        int[] a=new int[n];
        int[][] time = new int[n][10001];
        for(int i=0;i<n;i++){
            a[i]=in.nextInt()-1;
            dp[i]=-1;
        }

        for(int i=0;i<n;i++){
            int tmp=i;
            for(int j=1;j<10001;j++){
                tmp=a[tmp];
                time[i][j]=tmp;
            }
        }

        int ans=-1;
        for(int i=1;i<=10000;i++){
            boolean f=true;
            for(int j=0;j<n;j++){
                if(j!=time[time[j][i]][i]){
                    f=false;
                    break;
                }
            }
            if(f){
                ans=i;
                break;
            }
        }

/*        int mx=Integer.MIN_VALUE;
        for(int i=0;i<n;i++){
            t=0;
            dfs(a, i, new boolean[n], i);
            if(dp[i]==-1){
                ans=-1;
                break;
            }
            mx=max(mx,dp[i]);
        }
        if(ans!=-1){
            for(int t=1;t<=mx;t++){
                boolean f=true;
                for(int i=0;i<n;i++){
                    int tmp=i;
                    for(int k=0;k<t;k++){
                        tmp=a[tmp];
                    }
                    for(int k=0;k<t;k++){
                        tmp=a[tmp];
                    }
                    if(tmp!=i){
                        f=false;
                         break;
                    }
                }
                if(f){
                    ans=t;
                    break;
                }
            }
        }*/
        w.println(ans);
        w.close();
    }

    static class Pair{
		int x;
		int y;
		Pair(int x,int y){
			this.x=x;
			this.y=y;
		}
	}

    public static class CompareTable implements Comparator{
        public int compare(Object o1,Object o2){
            Pair p1 = (Pair) o1;
            Pair p2 = (Pair) o2;

            if(p1.x>p2.x)
                return -1;
            else if(p1.x<p2.x)
                return 1;
            else{
                if(p1.y<p2.y)
                    return -1;
                else if(p1.y>p2.y)
                    return 1;
                else
                    return 0;
            }
        }
    }

    public static boolean isPal(String s){
        for(int i=0, j=s.length()-1;i<=j;i++,j--){
                if(s.charAt(i)!=s.charAt(j)) return false;
        }
        return true;
    }
    public static String rev(String s){
		StringBuilder sb=new StringBuilder(s);
		sb.reverse();
		return sb.toString();
    }

    public static long gcd(long x,long y){
	if(x%y==0)
		return y;
	else
		return gcd(y,x%y);
    }

    public static int gcd(int x,int y){
	if(x%y==0)
		return y;
	else
		return gcd(y,x%y);
    }

    public static long gcdExtended(long a,long b,long[] x){

        if(a==0){
            x[0]=0;
            x[1]=1;
            return b;
        }
        long[] y=new long[2];
        long gcd=gcdExtended(b%a, a, y);

        x[0]=y[1]-(b/a)*y[0];
        x[1]=y[0];

        return gcd;
    }

    public static int abs(int a,int b){
	return (int)Math.abs(a-b);
    }

    public static long abs(long a,long b){
	return (long)Math.abs(a-b);
    }

    public static int max(int a,int b){
	if(a>b)
		return a;
	else
		return b;
    }

    public static int min(int a,int b){
	if(a>b)
		return b;
	else
		return a;
    }

    public static long max(long a,long b){
	if(a>b)
		return a;
	else
		return b;
    }

    public static long min(long a,long b){
	if(a>b)
		return b;
	else
		return a;
    }

    public static long pow(long n,long p,long m){
	 long  result = 1;
	  if(p==0)
	    return 1;
	if (p==1)
	    return n;
	while(p!=0)
	{
	    if(p%2==1)
	        result *= n;
	    if(result>=m)
	    result%=m;
	    p >>=1;
	    n*=n;
	    if(n>=m)
	    n%=m;
	}
	return result;
    }

    public static long pow(long n,long p){
	long  result = 1;
	  if(p==0)
	    return 1;
	if (p==1)
	    return n;
	while(p!=0)
	{
	    if(p%2==1)
	        result *= n;
	    p >>=1;
	    n*=n;
	}
	return result;
    }

	static class InputReader {

		private final InputStream stream;
		private final byte[] buf = new byte[8192];
		private int curChar, snumChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public int snext() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public int nextInt() {
			int c = snext();
			while (isSpaceChar(c)) {
				c = snext();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = snext();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public long nextLong() {
			int c = snext();
			while (isSpaceChar(c)) {
				c = snext();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = snext();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n) {
			int a[] = new int[n];
			for (int i = 0; i < n; i++) {
				a[i] = nextInt();
			}
			return a;
		}

		public long[] nextLongArray(int n) {
			long a[] = new long[n];
			for (int i = 0; i < n; i++) {
				a[i] = nextInt();
			}
			return a;
		}

		public String readString() {
			int c = snext();
			while (isSpaceChar(c)) {
				c = snext();
			}
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = snext();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public String nextLine() {
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = snext();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public boolean isSpaceChar(int c) {
			if (filter != null)
				return filter.isSpaceChar(c);
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		public interface SpaceCharFilter {
			public boolean isSpaceChar(int ch);
		}
	}
}

import java.util.Scanner;

import java.util.Arrays;

public class Main {
  static final int INF = Integer.MAX_VALUE / 2;
  static int n;
  static int[] c;

  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);

    n = sc.nextInt();
    c = new int[n];
    for(int i = 0; i < n; i++){
      c[i] = sc.nextInt() - 1;
    }
    int[] deg = new int[n];
    Arrays.fill(deg, 1);
    for(int i = 0; i < n; i++){
      deg[c[i]]++;
    }

    int t = INF;
    for(int s = 0; s < n; s++){
      if(deg[s] <= 1){
        continue;
      }
      int v = s, d = 0, w = -1;
      do{
        w = v;
        v = c[v];
        ++d;
      }while(v != w && v != s);
      if(v == s && d > 1){
        if(d == 2){
          t = Math.min(t, 1);
        }
        else{
          t = Math.min(t, d);
        }
      }
    }

    if(t != INF){
      System.out.println(t);
    }
    else{
      System.out.println(-1);
    }
  }
}

import java.util.Scanner;

public class Solution {

    private static int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }

    private static int lcm(int a, int b) {
        int g = gcd(a, b);
        return a * (b / g);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] crush = new int[n];
        boolean[] inDegree = new boolean[n];
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
            if (inDegree[crush[i]]) {
                System.out.println(-1);
                return;
            }
            inDegree[crush[i]] = true;
        }
        boolean[] visited = new boolean[n];
        int answer = 1;

        for (int i = 0; i < n; i++) {
            if (visited[i])
                continue;
            int j = i;
            int length = 0;
            while (!visited[j]) {
                visited[j] = true;
                j = crush[i];
                length += 1;
            }
            if (length % 2 == 0)
                answer = lcm(answer, length / 2);
            else
                answer = lcm(answer, length);
        }

        System.out.println(answer);
    }
}

import java.util.Scanner;

import java.util.Arrays;

public class Main {
  static final int INF = Integer.MAX_VALUE / 2;
  static int n;
  static int[] c;

  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);

    n = sc.nextInt();
    c = new int[n];
    for(int i = 0; i < n; i++){
      c[i] = sc.nextInt() - 1;
    }
    int[] deg = new int[n];
    Arrays.fill(deg, 1);
    for(int i = 0; i < n; i++){
      deg[c[i]]++;
    }

    for(int i = 0; i < n; i++){
      if(deg[i] == 1){
        System.out.println(-1);
        return;
      }
    }

    int t = 1;
    for(int s = 0; s < n; s++){
      int v = s, d = 0, w = -1;
      do{
        w = v;
        v = c[v];
        ++d;
      }while(v != w && v != s);
      if(v == s && d != 2){
        t = (t * d) / gcd(t, d);
      }
    }

    System.out.println(t);
  }

  private static int gcd(int a, int b){
    if(a == 0){
      return b;
    }
    return gcd(b % a, a);
  }
}

import java.io.*;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;

public class C {

    final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

    void solve() throws IOException {
        int n = readInt();
        int[] crush = new int[n];
        int[] count = new int[n];
        for(int i = 0; i < n; i++) {
            crush[i] = readInt() - 1;
            count[crush[i]]++;
        }

        if(Arrays.stream(count).anyMatch(x -> x != 1)) {
            out.println(-1);
            return;
        }
        long res = 1;
        boolean[] used = new boolean[n];
        for(int i = 0; i < n; i++) {
            if(used[i]) continue;

            int cur = i;
            int step = 0;
            while (true) {
                used[cur] = true;
                step++;
                cur = crush[cur];
                if(cur == i) break;
            }
            if (step == 2) step = 1;
            long gcd = gcd(res, step);
            res *= step / gcd;
        }
        out.println(res);
    }
    long gcd(long a, long b) {
        if(a == 0) return b;
        if(b == 0) return a;
        if(a > b) return gcd(a%b, b);
        else return gcd(a, b % a);
    }

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    int[] readArr(int n) throws IOException {
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = readInt();
        }
        return res;
    }

    long[] readArrL(int n) throws IOException {
        long[] res = new long[n];
        for (int i = 0; i < n; i++) {
            res[i] = readLong();
        }
        return res;
    }

    public static void main(String[] args) {
        new C().run();
    }

    public void run() {
        try {
            long t1 = System.currentTimeMillis();
            init();
            solve();
            out.close();
            long t2 = System.currentTimeMillis();
            System.err.println("Time = " + (t2 - t1));
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
    }
}

import java.util.Scanner;

public class Solution {

    private static int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }

    private static int lcm(int a, int b) {
        int g = gcd(a, b);
        return a * (b / g);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] crush = new int[n];
        boolean[] inDegree = new boolean[n];
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
            if (inDegree[crush[i]]) {
                System.out.println(-1);
                return;
            }
            inDegree[crush[i]] = true;
        }
        boolean[] visited = new boolean[n];
        int answer = 1;

        for (int i = 0; i < n; i++) {
            if (visited[i])
                continue;
            int j = i;
            int length = 1;
            while (!visited[j]) {
                visited[j] = true;
                j = crush[i];
                length += 1;
            }
            if (length % 2  == 0)
                answer = lcm(answer, length / 2);
            else
                answer = lcm(answer, length);
        }

        System.out.println(answer);
    }
}

import java.io.*;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

import javax.print.attribute.HashAttributeSet;

import java.lang.*;
import java.math.*;
import java.text.DecimalFormat;
import java.lang.reflect.Array;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
public class D{
	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
	static long MOD = (long)(1e9+7);
	static long MOD2 = MOD*MOD;
	//static long MOD = 998244353;
	static FastReader sc = new FastReader();
	static int pInf = Integer.MAX_VALUE;
	static int nInf = Integer.MIN_VALUE;
	public static void main(String[] args){
		int test = 1;
		//test = sc.nextInt();
		while(test-->0)solve();
		out.flush();
		out.close();
	}
	static int a[],n;
	static boolean visit[];
	static int cycleLen(int x,int y) {
		if(x==y) {
			return 0;
		}
		if(visit[x]) {
			out.println(-1);
			System.exit(0);
		}
		visit[x] = true;
		return 1+cycleLen(a[x], y);
	}
	public static void solve() {
		n = sc.nextInt();
		a = new int[n];
		visit = new boolean[n];
		for(int i = 0 ; i <n; i++) {
			a[i] = sc.nextInt()-1;
		}
		long lcm = 1;
		for(int i = 0; i < n; i++) {
			if(!visit[i]) {
				long len = 1+cycleLen(a[i],i);
				if((len&1)==0) {
					len = len/2;
				}
				lcm = lcm(lcm, len);
			}
		}
		out.println(lcm);
	}
	public static int lowerBound(int key, ArrayList<Integer> A) {
		int s = 0;
		int e = A.size()-1;
		if(e==-1) {
			return 0;
		}
		int ans = -1;
		while(s<=e) {
			int m = s+(e-s)/2;
			if(A.get(m)>=key) {
				ans = m;
				e = m-1;
			}
			else {
				s = m+1;
			}
		}
		return ans==-1?s:ans;
	}
	public static int upperBound(int key, ArrayList<Integer> A) {
		int l = -1; //good;
		int r = A.size()-1;
		while(r-l>1) {
			int m = l+(r-l)/2;
			if(A.get(m)<=key) {
				l = m;
			}
			else {
				r = m;
			}
		}
		return l;
	}
	public static long c2(long n) {
		if((n&1)==0) {
			return mul(n/2, n-1);
		}
		else {
			return mul(n, (n-1)/2);
		}
	}
	public static long mul(long a, long b){
	    return ((a%MOD)*(b%MOD))%MOD;
	}
	public static long add(long a, long b){
	    return ((a%MOD)+(b%MOD))%MOD;
	}
	public static long sub(long a, long b){
	    return ((a%MOD)-(b%MOD))%MOD;
	}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Integer.lowestOneBit(i)   Equals k where k is the position of the first one in the binary
//Integer.highestOneBit(i)  Equals k where k is the position of the last one in the binary
//Integer.bitCount(i)       returns the number of one-bits
//Collections.sort(A,(p1,p2)->(int)(p2.x-p1.x)) To sort ArrayList in descending order wrt values of x.
//            Arrays.parallelSort(a,new Comparator<TPair>() {
//      		public int compare(TPair a,TPair b) {
//        			if(a.y==b.y) return a.x-b.x;
//        			return b.y-a.y;
//        		}
//        	});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PrimeFactors
    public static ArrayList<Long> primeFactors(long n) {
        ArrayList<Long> arr = new ArrayList<>();
        if (n % 2 == 0)
            arr.add((long) 2);
        while (n % 2 == 0)
            n /= 2;
        for (long i = 3; i <= Math.sqrt(n); i += 2) {
            int flag = 0;
            while (n % i == 0) {
                n /= i;
                flag = 1;
            }
            if (flag == 1)
                arr.add(i);
        }
        if (n > 2)
            arr.add(n);
        return arr;
    }
//Pair Class
	static class Pair implements Comparable<Pair>{
		int x;
		int y;
		int len;
		public Pair(int x, int y) {
			this.x = x;
			this.y = y;
			this.len = y-x+1;
		}
		@Override
		public int compareTo(Pair o) {
			if(this.x==o.x){
			    return (this.y-o.y);
			}
			return -1*(this.x-o.x);
		}
	}
	static class TPair implements Comparable<TPair>{
		int two;
		int three;
		int prime;
		public TPair(int two, int three, int prime) {
			this.two = two;
			this.three = three;
			this.prime = prime;
		}
		@Override
		public int compareTo(TPair o) {
			if(this.three==o.three){
			    return (this.two-o.two);
			}
			return -1*(this.three-o.three);
		}
	}
//nCr
	static long ncr(long n, long k) {
        long ret = 1;
        for (long x = n; x > n - k; x--) {
            ret *= x;
            ret /= (n - x + 1);
        }

        return ret;
    }
	static long finextDoubleMMI_fermat(long n,int M)
    {
        return fastExpo(n,M-2);
    }

    static long nCrModPFermat(int n, int r, int p)
    {
        if (r == 0)
            return 1;
        long[] fac = new long[n+1];
        fac[0] = 1;
        for (int i = 1 ;i <= n; i++)
            fac[i] = fac[i-1] * i % p;
        return (fac[n]* finextDoubleMMI_fermat(fac[r], p)% p * finextDoubleMMI_fermat(fac[n-r], p) % p) % p;
    }
//Kadane's Algorithm
    static long maxSubArraySum(ArrayList<Long> a) {
    	if(a.size()==0) {
    		return 0;
    	}
    	long max_so_far = a.get(0);
    	long curr_max = a.get(0);
    	for (int i = 1; i < a.size(); i++) {
           curr_max = Math.max(a.get(i), curr_max+a.get(i));
           max_so_far = Math.max(max_so_far, curr_max);
    	}
    	return max_so_far;
    }
//Shuffle Sort
    static final Random random=new Random();
	static void ruffleSort(int[] a) {
		int n=a.length;//shuffle, then sort
		for (int i=0; i<n; i++) {
			int oi=random.nextInt(n), temp=a[oi];
			a[oi]=a[i]; a[i]=temp;
		}
		Arrays.sort(a);
	}
//Merge Sort
	static void merge(long arr[], int l, int m, int r)
    {
        // Find sizes of two subarrays to be merged
        int n1 = m - l + 1;
        int n2 = r - m;

        /* Create temp arrays */
        long L[] = new long [n1];
        long R[] = new long [n2];

        /*Copy data to temp arrays*/
        for (int i=0; i<n1; ++i)
            L[i] = arr[l + i];
        for (int j=0; j<n2; ++j)
            R[j] = arr[m + 1+ j];

        /* Merge the temp arrays */

        // Initial indexes of first and second subarrays
        int i = 0, j = 0;

        // Initial index of merged subarry array
        int k = l;
        while (i < n1 && j < n2)
        {
            if (L[i] <= R[j])
            {
                arr[k] = L[i];
                i++;
            }
            else
            {
                arr[k] = R[j];
                j++;
            }
            k++;
        }

        /* Copy remaining elements of L[] if any */
        while (i < n1)
        {
            arr[k] = L[i];
            i++;
            k++;
        }

        /* Copy remaining elements of R[] if any */
        while (j < n2)
        {
            arr[k] = R[j];
            j++;
            k++;
        }
    }

    // Main function that sorts arr[l..r] using
    // merge()
    static void sort(long arr[], int l, int r)
    {
        if (l < r)
        {
            // Find the middle point
            int m = (l+r)/2;

            // Sort first and second halves
            sort(arr, l, m);
            sort(arr , m+1, r);

            // Merge the sorted halves
            merge(arr, l, m, r);
        }
    }
//Brian Kernighans Algorithm
    static long countSetBits(long n){
        if(n==0) return 0;
        return 1+countSetBits(n&(n-1));
    }
//Factorial
    static long factorial(long n){
        if(n==1) return 1;
        if(n==2) return 2;
        if(n==3) return 6;
        return n*factorial(n-1);
    }
//Euclidean Algorithm
    static long lcm(long A,long B) {
    	return (A*B)/gcd(A, B);
    }
    static long gcd(long A,long B){
        if(B==0) return A;
        return gcd(B,A%B);
    }
//Modular Exponentiation
    static long fastExpo(long x,long n){
        if(n==0) return 1;
        if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
        return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
    }
//AKS Algorithm
    static boolean isPrime(long n){
        if(n<=1) return false;
        if(n<=3) return true;
        if(n%2==0 || n%3==0) return false;
        for(int i=5;i<=Math.sqrt(n);i+=6)
            if(n%i==0 || n%(i+2)==0) return false;
        return true;
    }
//Reverse an array
    static <T> void reverse(T arr[],int l,int r){
    	Collections.reverse(Arrays.asList(arr).subList(l, r));
    }
  //Print array
    static void print1d(int arr[]) {
    	out.println(Arrays.toString(arr));
    }
    static void print2d(int arr[][]) {
    	for(int a[]: arr) out.println(Arrays.toString(a));
    }
//Sieve of eratosthenes
    static int[] findPrimes(int n){
        boolean isPrime[]=new boolean[n+1];
        ArrayList<Integer> a=new ArrayList<>();
        int result[];
        Arrays.fill(isPrime,true);
        isPrime[0]=false;
        isPrime[1]=false;
        for(int i=2;i*i<=n;++i){
            if(isPrime[i]==true){
                for(int j=i*i;j<=n;j+=i) isPrime[j]=false;
            }
        }
        for(int i=0;i<=n;i++) if(isPrime[i]==true) a.add(i);
        result=new int[a.size()];
        for(int i=0;i<a.size();i++) result[i]=a.get(i);
        return result;

    }
//Indivisual factors of all nos till n
    static ArrayList<Integer>[] indiFactors(int n){
    	ArrayList<Integer>[] A = new ArrayList[n+1];
    	for(int i = 0; i <= n; i++) {
    		A[i] = new ArrayList<>();
    	}
    	int[] sieve = new int[n+1];
    	for(int i=2;i<=n;i++) {
       		if(sieve[i]==0) {
       			for(int j=i;j<=n;j+=i) if(sieve[j]==0) {
       				//sieve[j]=i;
       				A[j].add(i);
       			}
       		}
       	}
    	return A;
    }
//Segmented Sieve
    static boolean[] segmentedSieve(long l, long r){
    	boolean[] segSieve = new boolean[(int)(r-l+1)];
    	Arrays.fill(segSieve, true);
    	int[] prePrimes = findPrimes((int)Math.sqrt(r));
    	for(int p:prePrimes) {
    		long low = (l/p)*p;
    		if(low < l) {
    			low += p;
    		}
    		if(low == p) {
    			low += p;
    		}
    		for(long j = low; j<= r; j += p) {
    			segSieve[(int) (j-l)] = false;
    		}
    	}
    	if(l==1) {
    		segSieve[0] = false;
    	}
    	return segSieve;
    }
//Euler Totent function
    static long countCoprimes(long n){
        ArrayList<Long> prime_factors=new ArrayList<>();
        long x=n,flag=0;
        while(x%2==0){
            if(flag==0) prime_factors.add(2L);
            flag=1;
            x/=2;
        }
        for(long i=3;i*i<=x;i+=2){
            flag=0;
            while(x%i==0){
                if(flag==0) prime_factors.add(i);
                flag=1;
                x/=i;
            }
        }
        if(x>2) prime_factors.add(x);
        double ans=(double)n;
        for(Long p:prime_factors){
            ans*=(1.0-(Double)1.0/p);
        }
        return (long)ans;
    }
	static long modulo = (long)1e9+7;
	public static long modinv(long x){
	    return modpow(x, modulo-2);
	}
	public static long modpow(long a, long b){
	    if(b==0){
	        return 1;
	    }
	    long x = modpow(a, b/2);
	    x = (x*x)%modulo;
	    if(b%2==1){
	        return (x*a)%modulo;
	    }
	    return x;
	}
	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;
		//it reads the data about the specified point and divide the data about it ,it is quite fast
		//than using direct

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception r) {
					r.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());//converts string to integer
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception r) {
				r.printStackTrace();
			}
			return str;
		}
	}
}

import java.util.*;
import java.io.*;

public class Main {

	public static void main(String[] args) throws IOException {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int[] crush = new int[n];
		for(int i = 0; i < n; i++) crush[i] = in.nextInt() - 1;

		int ans = Integer.MIN_VALUE;
		Set<Integer> cycle = new HashSet<>();
		Set<Integer> visited = new HashSet<>();

		for(int i = 0; i < n; i++) {
			if(!visited.contains(i)) {
				int src = i;
				visited.add(i);
				cycle.add(i);

				int cursor = src;
				while(!cycle.contains(crush[cursor])) {
					if(visited.contains(crush[cursor])) {
						System.out.println("-1");
						return;
					}
					cursor = crush[cursor];
					visited.add(cursor);
					cycle.add(cursor);
				}

				if(src == crush[cursor]) {
					ans = Math.max(ans, cycle.size() % 2 == 0 ? cycle.size() / 2 : cycle.size());
					cycle.clear();
				} else {
					System.out.println("-1");
					return;
				}
			}
		}

		System.out.println(ans);
	}
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class A {

	static StringTokenizer st;
	static BufferedReader br;
	static PrintWriter pw;
	static int[]to, time;
	static boolean[]used;
	static int timer;
	static int ans = -1;
	static ArrayList<Integer>cicles;
	static int sum = 0;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int n = nextInt();
		to = new int[n+1];
		for (int i = 1; i <= n; i++) {
			to[i] = nextInt();
		}
		used = new boolean[n+1];
		cicles = new ArrayList<>();
		time = new int[n+1];
		for (int i = 1; i <= n; i++) {
			if (!used[i]) {
				dfs(i);
			}
		}
		if (sum != n) {
			System.out.println(-1);
			return;
		}
		BigInteger ans = BigInteger.ONE;
		for (int i : cicles) {
			ans = ans.multiply(BigInteger.valueOf(i)).divide(ans.gcd(BigInteger.valueOf(i)));
		}
		System.out.println(ans);
		pw.close();
	}
	private static void dfs(int v) {
		used[v] = true;
		time[v] = timer++;
		if (!used[to[v]])
			dfs(to[v]);
		else {
			int leng = time[v] - time[to[v]] + 1;
			if (leng % 2==0)
				cicles.add(leng / 2);
			else
				cicles.add(leng);
			sum += leng;
		}
	}
	private static int nextInt() throws IOException {
		return Integer.parseInt(next());
	}
	private static long nextLong() throws IOException {
		return Long.parseLong(next());
	}
	private static double nextDouble() throws IOException {
		return Double.parseDouble(next());
	}
	private static String next() throws IOException {
		while (st==null || !st.hasMoreTokens())
			st = new StringTokenizer(br.readLine());
		return st.nextToken();
	}
}

import java.util.*;
import java.io.*;

public final class ProblemC {
    private static boolean hasVertexWithZeroInDegree(final int[] out) {
        final int[] in = new int[out.length];
        for (int to: out) {
            in[to]++;
        }
        for (int indegree: in) {
            if (indegree == 0) {
                return true;
            }
        }
        return false;
    }

    private static int cycleLength(
            final int[] out,
            final int i,
            final boolean[] visited) {
        visited[i] = true;
        int length = 1;
        for (int to = out[i]; to != i;) {
            length++;
            visited[to] = true;
            to = out[to];
        }
        return length;
    }

    private static int gcd(final int a, final int b) {
        if (a < b) {
            return gcd(b, a);
        } else if (b == 0) {
            return a;
        } else {
            return gcd(b, a % b);
        }
    }

    private static int lcm(final int a, final int b) {
        return a / gcd(a, b) * b;
    }

    public static void main(final String[] args) {
        final Scanner in = new Scanner(System.in);
        final int n = in.nextInt();
        final int[] crush = new int[n];
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
        }
        if (hasVertexWithZeroInDegree(crush)) {
            System.out.println(-1);
            return;
        }

        List<Integer> cycles = new ArrayList<>();
        final boolean[] visited = new boolean[n];
        for (int i = 0; i < n; i++) {
            if (visited[i]) {
                continue;
            }
            final int cycleLength = cycleLength(crush, i, visited);
            cycles.add(cycleLength);
        }

        if (cycles.size() == 1) {
            System.out.println(cycles.get(0));
        } else {
            int lcm = lcm(cycles.get(0), cycles.get(1));
            for (int i = 2; i < cycles.size(); i++) {
                lcm = lcm(lcm, cycles.get(i));
            }
            System.out.println(lcm);
        }
    }
}

import java.util.Scanner;

public class Solution {

    private static int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }

    private static int lcm(int a, int b) {
        int g = gcd(a, b);
        return a * (b / g);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] crush = new int[n];
        boolean[] inDegree = new boolean[n];
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
            if (inDegree[crush[i]]) {
                System.out.println(-1);
                return;
            }
            inDegree[crush[i]] = true;
        }
        boolean[] visited = new boolean[n];
        int answer = 1;

        for (int i = 0; i < n; i++) {
            int j = i;
            int length = 0;
            while (!visited[j]) {
                visited[j] = true;
                j = crush[i];
                length += 1;
            }
            if (length % 2 == 0)
                answer = lcm(answer, length / 2);
            else
                answer = lcm(answer, length);
        }

        System.out.println(answer);
    }
}

import java.util.*;
import java.io.*;

/**
 * @author Deepit-PC
 *
 */
public class ArpasLoudOwfAndMehrdadsEvilPlan {
    public static InputReader in;
    public static PrintWriter out;

    public static final int MOD = (int) (1e9 + 7);

    public static void main(String[] args) {
	in = new InputReader(System.in);
	out = new PrintWriter(System.out);

	int n = in.nextInt();
	int[] crush = new int[n + 1];
	for (int i = 1; i <= n; i++) {
	    crush[i] = in.nextInt();
	}

	boolean found = true;
	int[] cycle = new int[n + 1];
	boolean[] visited = new boolean[n + 1];
	for (int start = 1; start <= n; start++) {
	    visited = new boolean[n + 1];
	    int next = start;
	    while(!visited[next]) {
		visited[next] = true;
		next = crush[next];
		cycle[start]++;
	    }
	    if((cycle[start]&1) == 0) {
		cycle[start] /= 2;
	    }
	    if(next != start || cycle[start] == 0) {
		found = false;
		break;
	    }
	}
	//out.println(Arrays.toString(cycle));
	int ans = -1;
	if(found) {
	    ans = cycle[1];
	    for (int i = 2; i <= n; i++) {
		ans = (ans*cycle[i])/(gcd(cycle[i], ans));
	    }
	}
	out.println(ans);

	out.close();
    }

    public static int gcd(int x, int y) {
	if(y == 0) {
	    return x;
	}
	return gcd(y, x%y);
    }

    static class Node implements Comparable<Node> {
	int next;
	int dist;

	public Node(int u, int v) {
	    this.next = u;
	    this.dist = v;
	}

	public void print() {
	    out.println(next + " " + dist + " ");
	}

	public int compareTo(Node that) {
	    return Integer.compare(this.next, that.next);
	}
    }

    static class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[8192];
	private int curChar, snumChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
	    this.stream = stream;
	}

	public int snext() {
	    if (snumChars == -1)
		throw new InputMismatchException();
	    if (curChar >= snumChars) {
		curChar = 0;
		try {
		    snumChars = stream.read(buf);
		} catch (IOException e) {
		    throw new InputMismatchException();
		}
		if (snumChars <= 0)
		    return -1;
	    }
	    return buf[curChar++];
	}

	public int nextInt() {
	    int c = snext();
	    while (isSpaceChar(c))
		c = snext();
	    int sgn = 1;
	    if (c == '-') {
		sgn = -1;
		c = snext();
	    }
	    int res = 0;
	    do {
		if (c < '0' || c > '9')
		    throw new InputMismatchException();
		res *= 10;
		res += c - '0';
		c = snext();
	    } while (!isSpaceChar(c));
	    return res * sgn;
	}

	public long nextLong() {
	    int c = snext();
	    while (isSpaceChar(c))
		c = snext();
	    int sgn = 1;
	    if (c == '-') {
		sgn = -1;
		c = snext();
	    }
	    long res = 0;
	    do {
		if (c < '0' || c > '9')
		    throw new InputMismatchException();
		res *= 10;
		res += c - '0';
		c = snext();
	    } while (!isSpaceChar(c));
	    return res * sgn;
	}

	public int[] nextIntArray(int n) {
	    int a[] = new int[n];
	    for (int i = 0; i < n; i++)
		a[i] = nextInt();
	    return a;
	}

	public String readString() {
	    int c = snext();
	    while (isSpaceChar(c))
		c = snext();
	    StringBuilder res = new StringBuilder();
	    do {
		res.appendCodePoint(c);
		c = snext();
	    } while (!isSpaceChar(c));
	    return res.toString();
	}

	public boolean isSpaceChar(int c) {
	    if (filter != null)
		return filter.isSpaceChar(c);
	    return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public interface SpaceCharFilter {
	    public boolean isSpaceChar(int ch);
	}
    }
}

import java.io.*;
import java.util.LinkedList;
import java.util.Objects;
import java.util.StringTokenizer;

public final class Main {
    static char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    static char[] chars1 = {'#', '*', '&'};
    static char[] chars2 = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};

    static boolean oneColor = true;

    // x1<0
    // x1+k*2>0;
    // k*2>-x1;
    // k=-x1/2
    public void solve() {
        int n = in.nextInt();
        int[] crush = new int[100];
        int tmax = n;
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
            if (crush[i]==i){
                tmax--;
            }
        }
        int t = 1;
        while (t<=tmax) {
            for (int x = 0; x < n; x++) {
                boolean b = false;
                if (x != crush[x]) {
                    int z = t;
                    int y = x;
                    while (z >= 1) {
                        y = crush[y];
                        z--;
                    }
                    z=t;
                    int tmp=y;
                    while (z>=1){
                        y=crush[y];
                        z--;
                    }
                    if (y==x){
                        b=true;
                    }
                }
                if (b){
                    out.println(t);
                    return;
                }
            }
            t++;
        }
        out.println(-1);
    }

    static class Library {
        static boolean isPrime(int a) {
            if (a == 1) {
                return false;
            }
            for (int i = 2; i * i <= a; i++) {
                if (a % i == 0)
                    return false;
            }
            return true;
        }

        static long bpow(long x, long n, long m) {
            long count = 1;
            if (n == 0) {
                return 1;
            }
            while (n > 0) {
                if ((n & 1) == 1) {
                    count *= x;
                    count %= m;
                }
                x *= x;
                x %= m;
                n >>= 1;
            }
            return count % m;
        }

        static long GCD(long a, long b) {
            if (b == 0) return a;
            return GCD(b, a % b);
        }
    }

    class Pair<X, Y> implements Comparable<Pair<X, Y>> {

        public X first;
        public Y second;

        public Pair(X first, Y second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public int hashCode() {
            int hash = 7;
            hash = 11 * hash + Objects.hashCode(this.first);
            hash = 11 * hash + Objects.hashCode(this.second);
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Pair<?, ?> other = (Pair<?, ?>) obj;
            if (!Objects.equals(this.first, other.first)) {
                return false;
            }
            if (!Objects.equals(this.second, other.second)) {
                return false;
            }
            return true;
        }

        @Override
        public int compareTo(Pair<X, Y> p) {
            return ((Comparable<X>) first).compareTo(p.first);
        }

        @Override
        public String toString() {
            return first + " " + second;
        }
    }

    class Node<E> {
        E element;
        Node<E> next;
        Node<E> prev;

        Node(E element, Node next, Node prev) {
            this.element = element;
            this.next = next;
            this.prev = prev;
        }
    }

    //    -------------I/O-------------    \\
    private FScanner in;

    private PrintWriter out;

    public static void main(String[] args) {
        new Main().runIO();
    }

    void run() {
        try {
            in = new FScanner(new File("input.txt"));
            out = new PrintWriter(new BufferedWriter(new FileWriter(new File("output.txt"))));
            solve();
            out.close();
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    void runIO() {
        in = new FScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out));
        solve();
        out.close();
        in.close();
    }

    class FScanner {

        private BufferedReader br;
        private StringTokenizer st;

        public FScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
        }

        void useString(String s) {
            if (s != null) {
                st = new StringTokenizer(s);
            }
        }

        void updateST() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String next() {
            updateST();
            return st.nextToken();
        }

        Long[] nextLongArray() {
            updateST();
            LinkedList<Long> ll = new LinkedList<>();
            while (st.hasMoreElements()) {
                ll.add(Long.parseLong(st.nextToken()));
            }
            Long[] arr = new Long[1];
            return ll.toArray(arr);
        }

        Integer[] nextIntArray() {
            updateST();
            LinkedList<Integer> ll = new LinkedList<>();
            while (st.hasMoreElements()) {
                ll.add(Integer.parseInt(st.nextToken()));
            }
            Integer[] arr = new Integer[1];
            return ll.toArray(arr);
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            updateST();
            StringBuilder sb = new StringBuilder(st.nextToken());
            while (st.hasMoreElements()) {
                sb.append(st.nextToken());
            }
            return sb.toString();
        }

        void close() {
            try {
                br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

import java.util.*;
import java.io.*;

/**
 *
 * @author umang
 */

public class C741 {

    public static int mod = 1000000007;
    public static int[] dp;
    public static int t;

    public static void dfs(int[] a,int x,boolean[] visited,int n){
        visited[x]=true;
        t++;
        if(a[x]==n){
            dp[n]=t;
            return;
        }
        if(!visited[a[x]])
            dfs(a,a[x],visited,n);
    }

    public static void main(String[] args) {

        InputReader in = new InputReader(System.in);
        PrintWriter w = new PrintWriter(System.out);

        int n=in.nextInt();
        dp=new int[n];
        int[] a=new int[n];

        for(int i=0;i<n;i++){
            a[i]=in.nextInt()-1;
            dp[i]=-1;
        }
        int ans=0;
        int mx=Integer.MIN_VALUE;
        for(int i=0;i<n;i++){
            t=0;
            dfs(a, i, new boolean[n], i);
            if(dp[i]==-1){
                ans=-1;
                break;
            }
            mx=max(mx,dp[i]);
        }
        if(ans!=-1){
            for(int t=1;t<=mx;t++){
                boolean f=true;
                for(int i=0;i<n;i++){
                    int tmp=i;
                    for(int k=0;k<t;k++){
                        tmp=a[tmp];
                    }
                    for(int k=0;k<t;k++){
                        tmp=a[tmp];
                    }
                    if(tmp!=i){
                        f=false;
                         break;
                    }
                }
                if(f){
                    ans=t;
                    break;
                }
            }
        }
        w.println(ans);
        w.close();
    }

    static class Pair{
		int x;
		int y;
		Pair(int x,int y){
			this.x=x;
			this.y=y;
		}
	}

    public static class CompareTable implements Comparator{
        public int compare(Object o1,Object o2){
            Pair p1 = (Pair) o1;
            Pair p2 = (Pair) o2;

            if(p1.x>p2.x)
                return -1;
            else if(p1.x<p2.x)
                return 1;
            else{
                if(p1.y<p2.y)
                    return -1;
                else if(p1.y>p2.y)
                    return 1;
                else
                    return 0;
            }
        }
    }

    public static boolean isPal(String s){
        for(int i=0, j=s.length()-1;i<=j;i++,j--){
                if(s.charAt(i)!=s.charAt(j)) return false;
        }
        return true;
    }
    public static String rev(String s){
		StringBuilder sb=new StringBuilder(s);
		sb.reverse();
		return sb.toString();
    }

    public static long gcd(long x,long y){
	if(x%y==0)
		return y;
	else
		return gcd(y,x%y);
    }

    public static int gcd(int x,int y){
	if(x%y==0)
		return y;
	else
		return gcd(y,x%y);
    }

    public static long gcdExtended(long a,long b,long[] x){

        if(a==0){
            x[0]=0;
            x[1]=1;
            return b;
        }
        long[] y=new long[2];
        long gcd=gcdExtended(b%a, a, y);

        x[0]=y[1]-(b/a)*y[0];
        x[1]=y[0];

        return gcd;
    }

    public static int abs(int a,int b){
	return (int)Math.abs(a-b);
    }

    public static long abs(long a,long b){
	return (long)Math.abs(a-b);
    }

    public static int max(int a,int b){
	if(a>b)
		return a;
	else
		return b;
    }

    public static int min(int a,int b){
	if(a>b)
		return b;
	else
		return a;
    }

    public static long max(long a,long b){
	if(a>b)
		return a;
	else
		return b;
    }

    public static long min(long a,long b){
	if(a>b)
		return b;
	else
		return a;
    }

    public static long pow(long n,long p,long m){
	 long  result = 1;
	  if(p==0)
	    return 1;
	if (p==1)
	    return n;
	while(p!=0)
	{
	    if(p%2==1)
	        result *= n;
	    if(result>=m)
	    result%=m;
	    p >>=1;
	    n*=n;
	    if(n>=m)
	    n%=m;
	}
	return result;
    }

    public static long pow(long n,long p){
	long  result = 1;
	  if(p==0)
	    return 1;
	if (p==1)
	    return n;
	while(p!=0)
	{
	    if(p%2==1)
	        result *= n;
	    p >>=1;
	    n*=n;
	}
	return result;
    }

	static class InputReader {

		private final InputStream stream;
		private final byte[] buf = new byte[8192];
		private int curChar, snumChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public int snext() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public int nextInt() {
			int c = snext();
			while (isSpaceChar(c)) {
				c = snext();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = snext();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public long nextLong() {
			int c = snext();
			while (isSpaceChar(c)) {
				c = snext();
			}
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = snext();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n) {
			int a[] = new int[n];
			for (int i = 0; i < n; i++) {
				a[i] = nextInt();
			}
			return a;
		}

		public long[] nextLongArray(int n) {
			long a[] = new long[n];
			for (int i = 0; i < n; i++) {
				a[i] = nextInt();
			}
			return a;
		}

		public String readString() {
			int c = snext();
			while (isSpaceChar(c)) {
				c = snext();
			}
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = snext();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public String nextLine() {
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = snext();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public boolean isSpaceChar(int c) {
			if (filter != null)
				return filter.isSpaceChar(c);
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		public interface SpaceCharFilter {
			public boolean isSpaceChar(int ch);
		}
	}
}

/*

        HARSH KHATRI
        DA-IICT

                      */

import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class CF741A {

    static ArrayList<ArrayList<Integer>> makeDir(int v, int[] a) {

        ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
        for(int i =0; i<v; i++) {
            adj.add(new ArrayList<Integer>());
        }

        //Scanner in = new Scanner(System.in);
        FasterScanner in = new FasterScanner();

        for(int i=0; i<v; i++) {
            (adj.get(i)).add(a[i]-1);
        }

        return adj;
    }

    static int dfs(ArrayList<ArrayList<Integer>> adj, int index, int t) {

        int count = t;
        Stack<Integer> s = new Stack<Integer>();

        int curr;
        s.push(index);

        while(count>0 && !s.empty()) {

            curr = s.pop();
            //System.out.println("visited vertex "+(curr+1));

            for(int x : adj.get(curr) ) {
                s.push(x);
                count--;
            }

        }
        return ( s.pop() );
    }

    public static void main(String[] args) {

        FasterScanner in = new FasterScanner();
        int n = in.nextInt(), i, t = 1;
        int[] a = new int[n];
        boolean[] crush = new boolean[n];

        int same = 0;
        for(i = 0; i<n; i++) {
            a[i] = in.nextInt();
            if(a[i] == (i+1)) same++;
            crush[a[i]-1] = true;
        }

        boolean stop = false;
        for(i=0; i<n; i++) {
            if(!crush[i]) {
                System.out.println(-1);
                stop = true;
            }
        }

        if(!stop) {
        if(same==n) {
            System.out.println(1);
        }

        else {
            ArrayList<ArrayList<Integer>> adj = makeDir(n, a);
            boolean found = false;

            while(t<=n && !found) {
                for(i = 0; i<n; i++) {
                    if(i == dfs(adj, (dfs(adj, i, t)), t) && a[i]!=(i+1)) found = true;
                }
                t++;
            }

            if(found) System.out.println(t-1);
            else System.out.println(-1);
        }
        }
    }
}

class FasterScanner {
        private byte[] buf = new byte[1024];
        private int curChar;
        private int snumChars;

        public int read() {
          if (snumChars == -1)
        throw new InputMismatchException();
          if (curChar >= snumChars) {
        curChar = 0;
        try {
          snumChars = System.in.read(buf);
        } catch (IOException e) {
          throw new InputMismatchException();
        }
        if (snumChars <= 0)
          return -1;
          }
          return buf[curChar++];
        }

        public double nextDouble() {
          return Double.parseDouble(this.nextString());
        }

        public String nextLine() {
          int c = read();
          while (isSpaceChar(c))
        c = read();
          StringBuilder res = new StringBuilder();
          do {
        res.appendCodePoint(c);
        c = read();
          } while (!isEndOfLine(c));
          return res.toString();
        }

        public String nextString() {
          int c = read();
          while (isSpaceChar(c))
        c = read();
          StringBuilder res = new StringBuilder();
          do {
        res.appendCodePoint(c);
        c = read();
          } while (!isSpaceChar(c));
          return res.toString();
        }

        public long nextLong() {
          int c = read();
          while (isSpaceChar(c))
        c = read();
          int sgn = 1;
          if (c == '-') {
        sgn = -1;
        c = read();
          }
          long res = 0;
          do {
        if (c < '0' || c > '9')
          throw new InputMismatchException();
        res *= 10;
        res += c - '0';
        c = read();
          } while (!isSpaceChar(c));
          return res * sgn;
        }

        public int nextInt() {
          int c = read();
          while (isSpaceChar(c))
        c = read();
          int sgn = 1;
          if (c == '-') {
        sgn = -1;
        c = read();
          }
          int res = 0;
          do {
        if (c < '0' || c > '9')
          throw new InputMismatchException();
        res *= 10;
        res += c - '0';
        c = read();
          } while (!isSpaceChar(c));
          return res * sgn;
        }

        public int[] nextIntArray(int n) {
          int[] arr = new int[n];
          for (int i = 0; i < n; i++) {
        arr[i] = nextInt();
          }
          return arr;
        }

        public long[] nextLongArray(int n) {
          long[] arr = new long[n];
          for (int i = 0; i < n; i++) {
        arr[i] = nextLong();
          }
          return arr;
        }

        private boolean isSpaceChar(int c) {
          return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
          return c == '\n' || c == '\r' || c == -1;
        }
}

import java.util.Scanner;
public class ArpasLoudOwf {
	static int n;
	static int crush[];
	public static int JoonJoon(int curNode,int step)
	{
		if (step==0)
			return curNode;
		return JoonJoon(crush[curNode],step-1);
	}
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		crush = new int[n];
		for (int i=0;i<n;i++)
			crush[i] = sc.nextInt()-1;
		int maxT = 0;
		for (int t=1;t<=100;t++)
		{
			boolean flag = true;
			for (int i=0;i<n;i++)
			{
				int j = JoonJoon(i,t);
				if (JoonJoon(j,t)!=i)
				{
					flag = false;
					break;
				}
			}
			if (flag)
			{
				System.out.println(t);
				return;
			}
		}
		System.out.println(-1);
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int N = in.nextInt();
            int[] next = new int[N];
            for (int i = 0; i < N; i++) {
                next[i] = in.nextInt() - 1;
            }
            int[] match = new int[N];
            for (int i = 0; i < N; i++) {
                match[i] = i;
            }
            iter:
            for (int t = 1; t <= 5000; t++) {
                for (int j = 0; j < N; j++) {
                    match[j] = next[match[j]];
                }
                for (int j = 0; j < N; j++) {
                    if (j != match[match[j]]) {
                        continue iter;
                    }
                }
                out.println(t);
                return;
            }
            out.println(-1);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.util.*;
import java.io.*;
import java.math.*;
public class Main9
{
	static class Pair
	{
		ArrayList<Pair1> x;
		int y;
		Pair(ArrayList<Pair1> x ,int y)
		{
			this.x=new ArrayList<>(x);
			this.y=y;
		}
	}
	static class Pair1
	{
		int x;
		int y;
		Pair1(int x,int y)
		{
			this.x=x;
			this.y=y;
		}
	}
	static int mod=1000000007;
	public static int[] sort(int[] a)
	{
		int n=a.length;
		ArrayList<Integer> ar=new ArrayList<>();
		for(int i=0;i<a.length;i++)
		{
			ar.add(a[i]);
		}
		Collections.sort(ar);
		for(int i=0;i<n;i++)
		{
			a[i]=ar.get(i);
		}
		return a;
	}
	public static long pow(long a, long b)
    {
        long result=1;
        while(b>0)
        {
            if (b % 2 != 0)
            {
                result=(result*a)%mod;
                b--;
            }
            a=(a*a)%mod;
            b /= 2;
        }
        return result;
    }

    public static long gcd(long a, long b)
    {
        if (a == 0)
            return b;
        return gcd(b%a, a);
    }
	public static long lcm(long a, long b)
	{
		return a*(b/gcd(a,b));
	}
	static ArrayList<ArrayList<Integer>> graph;
	static public void main(String args[])throws IOException
	{
		int tt=1;
		StringBuilder sb=new StringBuilder();
		for(int ttt=1;ttt<=tt;ttt++)
		{
			int n=i();
			int[] a=new int[n];
			graph=new ArrayList<>();
			for(int i=0;i<n;i++)
				graph.add(new ArrayList<>());
			for(int i=0;i<n;i++)
			{
				a[i]=i()-1;
				graph.get(i).add(a[i]);
			}
			boolean[] visited=new boolean[n];
			int ans=0;
			ArrayList<Integer> ar1=new ArrayList<>();
			for(int i=0;i<n;i++)
			{
				if(visited[i]==false)
				{
					Queue<Integer> queue=new LinkedList<>();
					queue.add(i);
					visited[i]=true;
					int count=0;
					boolean flag=false;
					int[] parent=new int[n];
					while(queue.isEmpty()==false)
					{
						int num=queue.poll();
						count++;
						ArrayList<Integer> ar=graph.get(num);
						for(int j=0;j<ar.size();j++)
						{
							int num1=ar.get(j);
							if(visited[num1]==false)
							{
								parent[num1]=num;
								visited[num1]=true;
								queue.add(num1);
							}
							else if(visited[num1]==true && num1!=num)
							{
								flag=true;
							}
						}
					}
					if(flag==false)
					{
						if(count!=1)
						{
							ans=-1;
						}
					}
					else
					{
						if(count==2)
						{
							ar1.add(1);
						}
						else
						{
							ar1.add(count);
						}
					}
				}
			}
			if(ans==-1)
				pln("-1");
			else
			{
				long lcm=ar1.get(0);
				for(int i=1;i<ar1.size();i++)
				{
					lcm=lcm(lcm,(int)ar1.get(i));
				}
				pln(lcm+"");
			}
		}
		System.out.print(sb.toString());
	}
			/**/
	static InputReader in=new InputReader(System.in);
	static OutputWriter out=new OutputWriter(System.out);
	public static long l()
	{
		String s=in.String();
		return Long.parseLong(s);
	}
	public static void pln(String value)
	{
		System.out.println(value);
	}
	public static int i()
	{
		return in.Int();
	}
	public static String s()
	{
		return in.String();
	}
}
	class InputReader
	{
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public int read() {
			if (numChars== -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public int Int() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public String String() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public boolean isSpaceChar(int c) {
			if (filter != null)
				return filter.isSpaceChar(c);
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public String next() {
			return String();
		}

		public interface SpaceCharFilter {
			public boolean isSpaceChar(int ch);
		}
	}

	class OutputWriter {
		private final PrintWriter writer;

		public OutputWriter(OutputStream outputStream) {
			writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
		}

		public OutputWriter(Writer writer) {
			this.writer = new PrintWriter(writer);
		}

		public void print(Object...objects) {
			for (int i = 0; i < objects.length; i++) {
				if (i != 0)
					writer.print(' ');
				writer.print(objects[i]);
			}
		}

		public void printLine(Object...objects) {
			print(objects);
			writer.println();
		}

		public void close() {
			writer.close();
		}

		public void flush() {
			writer.flush();
		}

		}

		class IOUtils {

		public static int[] readIntArray(InputReader in, int size) {
			int[] array = new int[size];
			for (int i = 0; i < size; i++)
				array[i] = in.Int();
			return array;
		}

	}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author zodiacLeo
 */
public class Main
{
    public static void main(String[] args)
    {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        FastPrinter out = new FastPrinter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA
    {
        private int INF = ((int) 1e7);

        public void solve(int testNumber, FastScanner in, FastPrinter out)
        {
            int n = in.nextInt();
            int[][] g = new int[n][n];

            for (int i = 0; i < n; i++)
            {
                Arrays.fill(g[i], INF);
            }
            for (int i = 0; i < n; i++)
            {
                int to = in.nextInt() - 1;
                g[i][to] = 1;
            }

            for (int k = 0; k < n; k++)
            {
                for (int i = 0; i < n; i++)
                {
                    for (int j = 0; j < n; j++)
                    {
                        g[i][j] = Math.min(g[i][j], g[i][k] + g[k][j]);
                    }
                }
            }
//        for (int i = 0; i < n; i++)
//        {
//            for (int j = 0; j < n; j++)
//            {
//                out.printf("%10d", g[i][j]);
//            }
//            out.println();
//        }
            long res = 1;
            TreeSet<Integer> set = new TreeSet<>();
            for (int i = 0; i < n; i++)
            {
                if (g[i][i] == INF)
                {
                    out.println(-1);
                    return;
                }
                set.add(g[i][i]);
                res = lcm(res, g[i][i]);
            }
            if (set.size() == 1)
            {
                out.println(res / 2);
                return;
            }
            out.println(res);
        }

        private long lcm(long a, long b)
        {
            return a / gcd(a, b) * b;
        }

        private long gcd(long a, long b)
        {
            return b == 0 ? a : gcd(b, a % b);
        }

    }

    static class FastPrinter extends PrintWriter
    {
        public FastPrinter(OutputStream out)
        {
            super(out);
        }

        public FastPrinter(Writer out)
        {
            super(out);
        }

    }

    static class FastScanner
    {
        public BufferedReader br;
        public StringTokenizer st;

        public FastScanner(InputStream is)
        {
            br = new BufferedReader(new InputStreamReader(is));
        }

        public FastScanner(File f)
        {
            try
            {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
        }

        public String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                String s = null;
                try
                {
                    s = br.readLine();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
                if (s == null)
                    return null;
                st = new StringTokenizer(s);
            }
            return st.nextToken();
        }

        public int nextInt()
        {
            return Integer.parseInt(next());
        }

    }
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        ConsoleIO io = new ConsoleIO();
        new Main(io).solve();
        io.close();
    }
    ConsoleIO io;
    Main(ConsoleIO io) {
        this.io = io;
    }

    long MOD = 1_000_000_007;
    int N, M, K, Q;

    public void solve() {
        int n = io.ri();
        int[] map = new int[n];
        for(int i = 0;i<n;i++){
            int v = io.ri()-1;
            map[i] = v;
        }

        boolean[] used = new boolean[n];
        long res = 1;
        long div = 0;
        for(int i = 0;i<n;i++){
            if(!used[i]){
                int t = i;
                used[t] = true;
                int cur=map[i];
                int c = 1;
                while(!used[cur]){
                    c++;
                    used[cur] =true;
                    cur = map[cur];
                }
                if(cur!=t){
                    io.writeLine("-1");
                    return;
                }
                if(c%2==0)c/=2;
                res*=c;
                div = gcd(div, c);
            }
        }

        res/=div;

        io.writeLine(res + "");
    }

    long gcd(long a, long b) {
        if (a < b) return gcd(b, a);
        return b == 0 ? a : gcd(b, a % b);
    }

}

class ConsoleIO {
    BufferedReader br;
    PrintWriter out;
    public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);}
    public void flush(){this.out.flush();}
    public void close(){this.out.close();}
    public void writeLine(String s) {this.out.println(s);}
    public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
    public void writeWord(String s){
        this.out.print(s);
    }
    public void writeIntArray(int[] a, int k, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < k; i++) {
            if (i > 0) sb.append(separator);
            sb.append(a[i]);
        }
        this.writeLine(sb.toString());
    }
    public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
    public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
    public long[] readLongArray() {
        String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
        for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
        return r;
    }
    public int[] readIntArray() {
        String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
        for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
        return r;
    }
    public int[] readIntArray(int n) {
        int[] res = new int[n];
        char[] all = this.readLine().toCharArray();
        int cur = 0;boolean have = false;
        int k = 0;
        boolean neg = false;
        for(int i = 0;i<all.length;i++){
            if(all[i]>='0' && all[i]<='9'){
                cur = cur*10+all[i]-'0';
                have = true;
            }else if(all[i]=='-') {
                neg = true;
            }
            else if(have){
                res[k++] = neg?-cur:cur;
                cur = 0;
                have = false;
                neg = false;
            }
        }
        if(have)res[k++] = neg?-cur:cur;
        return res;
    }
    public int ri() {
        try {
            int r = 0;
            boolean start = false;
            boolean neg = false;
            while (true) {
                int c = br.read();
                if (c >= '0' && c <= '9') {
                    r = r * 10 + c - '0';
                    start = true;
                } else if (!start && c == '-') {
                    start = true;
                    neg = true;
                } else if (start || c == -1) return neg ? -r : r;
            }
        } catch (Exception ex) {
            return -1;
        }
    }
    public long readLong() {
        try {
            long r = 0;
            boolean start = false;
            boolean neg = false;
            while (true) {
                int c = br.read();
                if (c >= '0' && c <= '9') {
                    r = r * 10 + c - '0';
                    start = true;
                } else if (!start && c == '-') {
                    start = true;
                    neg = true;
                } else if (start || c == -1) return neg ? -r : r;
            }
        } catch (Exception ex) {
            return -1;
        }
    }
    public String readWord() {
        try {
            boolean start = false;
            StringBuilder sb = new StringBuilder();
            while (true) {
                int c = br.read();
                if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') {
                    sb.append((char)c);
                    start = true;
                } else if (start || c == -1) return sb.toString();
            }
        } catch (Exception ex) {
            return "";
        }
    }
    public char readSymbol() {
        try {
            while (true) {
                int c = br.read();
                if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
                    return (char) c;
                }
            }
        } catch (Exception ex) {
            return 0;
        }
    }
    public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }}
}
class Pair {
    public Pair(int a, int b) {this.a = a;this.b = b;}
    public int a;
    public int b;
}
class Tri {
    public Tri(int a, int b, int c) {this.a = a;this.b = b;this.c = c;}
    public int a;
    public int b;
    public int c;
}
class PairLL {
    public PairLL(long a, long b) {this.a = a;this.b = b;}
    public long a;
    public long b;
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Liavontsi Brechka
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        int n;
        int[] crush;
        int[] cycleLength;
        boolean[] isVisited;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            n = in.nextInt();
            crush = new int[n];
            isVisited = new boolean[n];
            cycleLength = new int[n];
            for (int i = 0; i < n; i++) {
                crush[i] = in.nextInt() - 1;
            }

            for (int i = 0; i < n; i++) {
                if (!isVisited[i]) {
                    dfs(i, 1, i);
                }
            }

            int res = -1;
            for (int i = 0; i < n; i++) {
                if (cycleLength[i] == Integer.MAX_VALUE) {
                    res = -1;
                    break;
                }
                if (res < cycleLength[i]) {
                    if (res > 2 && cycleLength[i] % res != 0) {
                        res = -1;
                        break;
                    } else {
                        res = cycleLength[i];
                    }
                }
            }

            out.print(res);
        }

        private int dfs(int u, int level, int origin) {
            isVisited[u] = true;
            if (!isVisited[crush[u]])
                cycleLength[u] = dfs(crush[u], level + 1, origin);
            else {
                if (crush[u] == origin) cycleLength[u] = level;
                else cycleLength[u] = Integer.MAX_VALUE;
            }
            return cycleLength[u] % 2 == 0 ? cycleLength[u] /= 2 : cycleLength[u];
        }

    }

    static class InputReader {
        private final BufferedReader reader;
        private StringTokenizer tokenizer;

        public InputReader(InputStream in) {
            reader = new BufferedReader(new InputStreamReader(in));
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                tokenizer = new StringTokenizer(readLine());
            }
            return tokenizer.nextToken();
        }

        public String readLine() {
            String line;
            try {
                line = reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return line;
        }

    }
}

import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;

public class Check2
{

	static class InputReader
	{
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream)
		{
			this.stream = stream;
		}

		public int read()
		{
			if (numChars==-1)
				throw new InputMismatchException();

			if (curChar >= numChars)
			{
				curChar = 0;
				try
				{
					numChars = stream.read(buf);
				}
				catch (IOException e)
				{
					throw new InputMismatchException();
				}

				if(numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public String nextLine()
		{
			BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
			String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
		}
		public int nextInt()
		{
			int c = read();

			while(isSpaceChar(c))
				c = read();

			int sgn = 1;

			if (c == '-')
			{
				sgn = -1;
				c = read();
			}

			int res = 0;
			do
			{
				if(c<'0'||c>'9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			}
			while (!isSpaceChar(c));

			return res * sgn;
		}

		public long nextLong()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-')
			{
				sgn = -1;
				c = read();
			}
			long res = 0;

			do
			{
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			}
			while (!isSpaceChar(c));
				return res * sgn;
		}

		public double nextDouble()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-')
			{
				sgn = -1;
				c = read();
			}
			double res = 0;
			while (!isSpaceChar(c) && c != '.')
			{
				if (c == 'e' || c == 'E')
					return res * Math.pow(10, nextInt());
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			}
			if (c == '.')
			{
				c = read();
				double m = 1;
				while (!isSpaceChar(c))
				{
					if (c == 'e' || c == 'E')
						return res * Math.pow(10, nextInt());
					if (c < '0' || c > '9')
						throw new InputMismatchException();
					m /= 10;
					res += (c - '0') * m;
					c = read();
				}
			}
			return res * sgn;
		}

		public String readString()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do
			{
				res.appendCodePoint(c);
				c = read();
			}
			while (!isSpaceChar(c));

			return res.toString();
		}

		public boolean isSpaceChar(int c)
		{
			if (filter != null)
				return filter.isSpaceChar(c);
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public String next()
		{
			return readString();
		}

		public interface SpaceCharFilter
		{
			public boolean isSpaceChar(int ch);
		}
	}

	public static void main(String args[]) throws Exception
	{
		InputReader sc=new InputReader(System.in);
		PrintWriter w=new PrintWriter(System.out);

		int n=sc.nextInt();

		int ip[]=new int[n+1];
		int flag[]=new int[n+1];

		int path[][]=new int[n+1][n+1];

		int main_flag=0;
		for(int i=1;i<=n;i++)
		{
			ip[i]=sc.nextInt();
			flag[ip[i]]++;
			if(flag[ip[i]]>1)
				main_flag=1;
		}

		if(main_flag==1)
			w.println("-1");
		else
		{
			for(int i=1;i<=n;i++)
			{
				int root=ip[i];
				for(int j=1;j<=n;j++)
				{
					path[i][j]=root;
					root=ip[root];
				}
			}

			int min=Integer.MAX_VALUE;
			int count=0;

			for(int i=1;i<=n;i++)
			{
				int ans=1;
				int check=ip[i];

				if(check==i)
				{
					count++;
					continue;
				}

				for(int j=1;j<=n;j++)
				{
					if(path[check][ans]==i)
						break;

					check=path[i][++ans];
				}
				min=Math.min(min,ans);
			}
			if(count==n)
				w.println("1");
			else
				w.println(min);
		}
		w.close();
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int N = in.nextInt();
            int[] next = new int[N];
            for (int i = 0; i < N; i++) {
                next[i] = in.nextInt() - 1;
            }
            iter:
            for (int t = 1; t <= N; t++) {
                int[] match = new int[N];
                for (int j = 0; j < N; j++) {
                    int tempT = t;
                    int cur = j;
                    while (tempT-- > 0) {
                        cur = next[cur];
                    }
                    match[j] = cur;
                }
                for (int j = 0; j < N; j++) {
                    if (j != match[match[j]]) {
                        continue iter;
                    }
                }
                out.println(t);
                return;
            }
            out.println(-1);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.util.*;
import java.io.*;
import java.time.chrono.MinguoChronology;

public class C {
	FastScanner in;
	PrintWriter out;
	boolean systemIO = true;

	public int dfs(int x, int t) {
		if (t == 0) {
			return x;
		}
		t--;
		return dfs(e[x], t);
	}

	int[] e;

	public void solve() {
		int n = in.nextInt();
		e = new int[n];
		for (int i = 0; i < e.length; i++) {
			e[i] = in.nextInt() - 1;
		}
		for (int t = 1; t < e.length + 2; t++) {
			boolean flag = true;
			for (int i = 0; i < e.length; i++) {
				int y = dfs(i, t);
				if (dfs(y, t) != i) {
					flag = false;
					break;
				}
			}
			if (flag) {
				out.println(t);
				out.close();
				return;
			}
		}
		out.println(-1);
	}

	public void run() {
		try {
			if (systemIO) {
				in = new FastScanner(System.in);
				out = new PrintWriter(System.out);
			} else {
				in = new FastScanner(new File("segments.in"));
				out = new PrintWriter(new File("segments.out"));
			}
			solve();

			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

		FastScanner(File f) {
			try {
				br = new BufferedReader(new FileReader(f));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		FastScanner(InputStream f) {
			br = new BufferedReader(new InputStreamReader(f));
		}

		String nextLine() {
			try {
				return br.readLine();
			} catch (IOException e) {
				return null;
			}
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

	}

	// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
	public static void main(String[] arg) {
		new C().run();
	}
}

/*
 * Remember a 6.0 student can know more than a 10.0 student.
 * Grades don't determine intelligence, they test obedience.
 * I Never Give Up.
 * I will become Candidate Master.
 * I will defeat Saurabh Anand.
 * Skills are Cheap,Passion is Priceless.
 */
import java.util.*;
import java.util.Map.Entry;
import java.io.*;

import static java.lang.System.out;
import static java.util.Arrays.*;
import static java.lang.Math.*;

public class ContestMain{
	private static Reader in=new Reader();
	private static StringBuilder ans=new StringBuilder();
	private static long MOD=1000000000+7;// 1e9+7
	private static final int N=200000+7; // 2e5+7
//    private static final double EPS=1e-9;
//    private static final int LIM=26;
//    private static final double PI=3.1415;
//    private static ArrayList<Integer> v[]=new ArrayList[N];
//    private static int color[]=new int[N];
	private static boolean mark[]=new boolean[N];

//    private static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//    private static ArrayList<Pair> v[]=new ArrayList[N];
	private static long powmod(long x,long n){
		if(n==0||x==0)
			return 1;
		else if(n%2==0)
			return(powmod((x*x)%MOD,n/2));
		else
			return (x*(powmod((x*x)%MOD,(n-1)/2)))%MOD;
	}

	private static void shuffle(long[] arr){
		for(int i=arr.length-1;i>=2;i--){
			int x=new Random().nextInt(i-1);
			long temp=arr[x];
			arr[x]=arr[i];
			arr[i]=temp;
		}
	}

//    private static long gcd(long a, long b){
//        if(b==0)return a;
//        return gcd(b,a%b);
//    }
//    private static boolean check(int x,int y){
//        if((x>=0&&x<n)&&(y>=0&&y<m)&&mat[x][y]!='X'&&!visited[x][y])return true;
//        return false;
//    }
	public static void main(String[] args) throws IOException{
		int n=in.nextInt();
		int ar[]=new int[n+1];
		for(int i=1;i<=n;i++)
			ar[i]=in.nextInt();
		int node=0;
		HashSet<Integer> set=new HashSet();
		HashSet<Integer> resSet=new HashSet();
		boolean flag;
		for(int i=1;i<=n;i++){
			node=i;
			flag=false;
			while(true){
				if(set.contains(node)){
					if(node==i)flag=true;
					else flag=false;
					break;
				}
				set.add(node);
				node=ar[node];
			}
			resSet.add(set.size());
			set.clear();
			if(!flag){out.println(-1);return;}
		}
		long res=1;
		for(int a:resSet){
			if(a!=2)res=res*a;
		}
		out.println(res);
	}
	static class Pair<T> implements Comparable<Pair>{
		long l;
		long r;

		Pair(){
			l=0;
			r=0;
		}

		Pair(long k,long v){
			l=k;
			r=v;
		}

		@Override
		public int compareTo(Pair o){
			if(o.l!=l)
				return (int)-(l-o.l);
			else
				return (int)(r-o.r);
		}
		// Fenwick tree question comparator
//        @Override
//        public int compareTo(Pair o) {
//            if(o.r!=r)return (int) (r-o.r);
//            else return (int)(l-o.l);
//        }
	}

	static class Reader{
		BufferedReader br;
		StringTokenizer st;

		public Reader(){
			br=new BufferedReader(new InputStreamReader(System.in));
		}

		String next(){
			while(st==null||!st.hasMoreElements()){
				try{

					st=new StringTokenizer(br.readLine());
				}catch(IOException e){
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt(){
			return Integer.parseInt(next());
		}

		long nextLong(){
			return Long.parseLong(next());
		}

		double nextDouble(){
			return Double.parseDouble(next());
		}

		String nextLine(){
			String str="";
			try{
				str=br.readLine();
			}catch(IOException e){
				e.printStackTrace();
			}
			return str;
		}
	}
}

//package baobab;

import java.io.*;
import java.util.*;

public class C {

    public static void main(String[] args) {
        Solver solver = new Solver();
    }

    static class Solver {
        IO io;

        public Solver() {
            this.io = new IO();
            try {
                solve();
            } finally {
                io.close();
            }
        }

        /****************************** START READING HERE ********************************/

        void solve() {
            int n = io.nextInt();
            int[] crush = new int[n+1];
            for (int i=1; i<=n; i++) {
                crush[i] = io.nextInt();
            }
            HashSet<Integer> possibles = new HashSet<>();
            for (int start=1; start<=n; start++) {
                int t = 0;
                int curr = start;
                boolean[] vis = new boolean[n+1];
                while (!vis[curr]) {
                    vis[curr] = true;
                    curr = crush[curr];
                    t++;
                }
                if (curr != start) {
                    io.println(-1);
                    return;
                }
                if (t%2 == 0) {
                    t /= 2;
                }
                possibles.add(t);
            }

            for (int i=1; i<=100000; i++) {
                if (possible4all(possibles, i)) {
                    io.println(i);
                    return;
                }
            }

            io.println(-1);
        }

        boolean possible4all(HashSet<Integer> possibles, int i) {
            for (Integer p : possibles) {
                if (i % p != 0) return false;
            }
            return true;
        }

        /************************** UTILITY CODE BELOW THIS LINE **************************/

        long MOD = (long)1e9 + 7;

        List<Integer>[] toGraph(IO io, int n) {
            List<Integer>[] g = new ArrayList[n+1];
            for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
            for (int i=1; i<=n-1; i++) {
                int a = io.nextInt();
                int b = io.nextInt();
                g[a].add(b);
                g[b].add(a);
            }
            return g;
        }

        class Point {
            int y;
            int x;

            public Point(int y, int x) {
                this.y = y;
                this.x = x;
            }
        }

        class IDval implements Comparable<IDval> {
            int id;
            long val;

            public IDval(int id, long val) {
                this.val = val;
                this.id = id;
            }

            @Override
            public int compareTo(IDval o) {
                if (this.val < o.val) return -1;
                if (this.val > o.val) return 1;
                return this.id - o.id;
            }
        }

        long pow(long base, int exp) {
            if (exp == 0) return 1L;
            long x = pow(base, exp/2);
            long ans = x * x;
            if (exp % 2 != 0) ans *= base;
            return ans;
        }

        class ElementCounter {
            private HashMap<Long, Long> elements;

            public ElementCounter() {
                elements = new HashMap<>();
            }

            public void add(long element) {
                long count = 1;
                if (elements.containsKey(element)) count += elements.get(element);
                elements.put(element, count);
            }

            public void remove(long element) {
                long count = elements.get(element);
                count--;
                if (count == 0) elements.remove(element);
                else elements.put(element, count);
            }

            public long get(long element) {
                if (!elements.containsKey(element)) return 0;
                return elements.get(element);
            }

            public int size() {
                return elements.size();
            }
        }

        class StringCounter {
            HashMap<String, Long> elements;

            public StringCounter() {
                elements = new HashMap<>();
            }

            public void add(String identifier) {
                long count = 1;
                if (elements.containsKey(identifier)) count += elements.get(identifier);
                elements.put(identifier, count);
            }

            public void remove(String identifier) {
                long count = elements.get(identifier);
                count--;
                if (count == 0) elements.remove(identifier);
                else elements.put(identifier, count);
            }

            public long get(String identifier) {
                if (!elements.containsKey(identifier)) return 0;
                return elements.get(identifier);
            }

            public int size() {
                return elements.size();
            }
        }

        class LCAFinder {

            /* O(n log n) Initialize: new LCAFinder(graph)
             * O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */

            int[] nodes;
            int[] depths;
            int[] entries;
            int pointer;
            FenwickMin fenwick;

            public LCAFinder(List<Integer>[] graph) {
                this.nodes = new int[(int)10e6];
                this.depths = new int[(int)10e6];
                this.entries = new int[graph.length];
                this.pointer = 1;
                boolean[] visited = new boolean[graph.length+1];
                dfs(1, 0, graph, visited);
                fenwick = new FenwickMin(pointer-1);
                for (int i=1; i<pointer; i++) {
                    fenwick.set(i, depths[i] * 1000000L + i);
                }
            }

            private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
                visited[node] = true;
                entries[node] = pointer;
                nodes[pointer] = node;
                depths[pointer] = depth;
                pointer++;
                for (int neighbor : graph[node]) {
                    if (visited[neighbor]) continue;
                    dfs(neighbor, depth+1, graph, visited);
                    nodes[pointer] = node;
                    depths[pointer] = depth;
                    pointer++;
                }
            }

            public int find(int a, int b) {
                int left = entries[a];
                int right = entries[b];
                if (left > right) {
                    int temp = left;
                    left = right;
                    right = temp;
                }
                long mixedBag = fenwick.getMin(left, right);
                int index = (int) (mixedBag % 1000000L);
                return nodes[index];
            }
        }

        class FenwickMin {
            long n;
            long[] original;
            long[] bottomUp;
            long[] topDown;

            public FenwickMin(int n) {
                this.n = n;
                original = new long[n+2];
                bottomUp = new long[n+2];
                topDown = new long[n+2];
            }

            public void set(int modifiedNode, long value) {
                long replaced = original[modifiedNode];
                original[modifiedNode] = value;
                // Update left tree
                int i = modifiedNode;
                long v = value;
                while (i <= n) {
                    if (v > bottomUp[i]) {
                        if (replaced == bottomUp[i]) {
                            v = Math.min(v, original[i]);
                            for (int r=1 ;; r++) {
                                int x = (i&-i)>>>r;
                                if (x == 0) break;
                                int child = i-x;
                                v = Math.min(v, bottomUp[child]);
                            }
                        } else break;
                    }
                    if (v == bottomUp[i]) break;
                    bottomUp[i] = v;
                    i += (i&-i);
                }
                // Update right tree
                i = modifiedNode;
                v = value;
                while (i > 0) {
                    if (v > topDown[i]) {
                        if (replaced == topDown[i]) {
                            v = Math.min(v, original[i]);
                            for (int r=1 ;; r++) {
                                int x = (i&-i)>>>r;
                                if (x == 0) break;
                                int child = i+x;
                                if (child > n+1) break;
                                v = Math.min(v, topDown[child]);
                            }
                        } else break;
                    }
                    if (v == topDown[i]) break;
                    topDown[i] = v;
                    i -= (i&-i);
                }
            }

            public long getMin(int a, int b) {
                long min = original[a];
                int prev = a;
                int curr = prev + (prev&-prev); // parent right hand side
                while (curr <= b) {
                    min = Math.min(min, topDown[prev]); // value from the other tree
                    prev = curr;
                    curr = prev + (prev&-prev);;
                }
                min = Math.min(min, original[prev]);
                prev = b;
                curr = prev - (prev&-prev); // parent left hand side
                while (curr >= a) {
                    min = Math.min(min,bottomUp[prev]); // value from the other tree
                    prev = curr;
                    curr = prev - (prev&-prev);
                }
                return min;
            }

        }

        class FenwickSum {
            public long[] d;

            public FenwickSum(int n) {
                d=new long[n+1];
            }

            /** a[0] must be unused. */
            public FenwickSum(long[] a) {
                d=new long[a.length];
                for (int i=1; i<a.length; i++) {
                    modify(i, a[i]);
                }
            }

            /** Do not modify i=0. */
            void modify(int i, long v) {
                while (i<d.length) {
                    d[i] += v;
                    // Move to next uplink on the RIGHT side of i
                    i += (i&-i);
                }
            }

            /** Returns sum from a to b, *BOTH* inclusive. */
            long getSum(int a, int b) {
                return getSum(b) - getSum(a-1);
            }

            private long getSum(int i) {
                long sum = 0;
                while (i>0) {
                    sum += d[i];
                    // Move to next uplink on the LEFT side of i
                    i -= (i&-i);
                }
                return sum;
            }
        }

        class SegmentTree {
            /** Query sums with log(n) modifyRange */
            int N;
            long[] p;

            public SegmentTree(int n) {
                /* TODO: Test that this works. */
                N = n;
                p = new long[2*N];
            }

            public void modifyRange(int a, int b, long change) {
                muuta(a, change);
                muuta(b+1, -change);
            }

            void muuta(int k, long muutos) {
                k += N;
                p[k] += muutos;
                for (k /= 2; k >= 1; k /= 2) {
                    p[k] = p[2*k] + p[2*k+1];
                }
            }

            public long get(int k) {
                int a = N;
                int b = k+N;
                long s = 0;
                while (a <= b) {
                    if (a%2 == 1) s += p[a++];
                    if (b%2 == 0) s += p[b--];
                    a /= 2;
                    b /= 2;
                }
                return s;
            }

        }

        class Zalgo {

            public int pisinEsiintyma(String haku, String kohde) {
                char[] s = new char[haku.length() + 1 + kohde.length()];
                for (int i=0; i<haku.length(); i++) {
                    s[i] = haku.charAt(i);
                }
                int j = haku.length();
                s[j++] = '#';
                for (int i=0; i<kohde.length(); i++) {
                    s[j++] = kohde.charAt(i);
                }
                int[] z = toZarray(s);
                int max = 0;
                for (int i=haku.length(); i<z.length; i++) {
                    max = Math.max(max, z[i]);
                }
                return max;
            }

            public int[] toZarray(char[] s) {
                int n = s.length;
                int[] z = new int[n];
                int a = 0, b = 0;
                for (int i = 1; i < n; i++) {
                    if (i > b) {
                        for (int j = i; j < n && s[j - i] == s[j]; j++)  z[i]++;
                    }
                    else {
                        z[i] = z[i - a];
                        if (i + z[i - a] > b) {
                            for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
                            a = i;
                            b = i + z[i] - 1;
                        }
                    }
                }
                return z;
            }

            public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
                // this is alternative use case
                char[] s = new char[haku.length() + 1 + kohde.length()];
                for (int i=0; i<haku.length(); i++) {
                    s[i] = haku.charAt(i);
                }
                int j = haku.length();
                s[j++] = '#';
                for (int i=0; i<kohde.length(); i++) {
                    s[j++] = kohde.charAt(i);
                }
                int[] z = toZarray(s);
                List<Integer> indexes = new ArrayList<>();
                for (int i=haku.length(); i<z.length; i++) {
                    if (z[i] < haku.length()) continue;
                    indexes.add(i);
                }
                return indexes;
            }

        }

        class StringHasher {

            class HashedString {
                long[] hashes;
                long[] modifiers;

                public HashedString(long[] hashes, long[] modifiers) {
                    this.hashes = hashes;
                    this.modifiers = modifiers;
                }
            }

            long P;
            long M;

            public StringHasher() {
                initializePandM();
            }

            HashedString hashString(String s) {
                int n = s.length();
                long[] hashes = new long[n];
                long[] modifiers = new long[n];
                hashes[0] = s.charAt(0);
                modifiers[0] = 1;
                for (int i=1; i<n; i++) {
                    hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
                    modifiers[i] = (modifiers[i-1] * P) % M;
                }
                return new HashedString(hashes, modifiers);
            }

            /**
             * Indices are inclusive.
             */
            long getHash(HashedString hashedString, int startIndex, int endIndex) {
                long[] hashes = hashedString.hashes;
                long[] modifiers = hashedString.modifiers;
                long result = hashes[endIndex];
                if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
                if (result < 0) result += M;
                return result;
            }

            // Less interesting methods below

            /**
             * Efficient for 2 input parameter strings in particular.
             */
            HashedString[] hashString(String first, String second) {
                HashedString[] array = new HashedString[2];
                int n = first.length();
                long[] modifiers = new long[n];
                modifiers[0] = 1;

                long[] firstHashes = new long[n];
                firstHashes[0] = first.charAt(0);
                array[0] = new HashedString(firstHashes, modifiers);

                long[] secondHashes = new long[n];
                secondHashes[0] = second.charAt(0);
                array[1] = new HashedString(secondHashes, modifiers);

                for (int i=1; i<n; i++) {
                    modifiers[i] = (modifiers[i-1] * P) % M;
                    firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
                    secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
                }
                return array;
            }

            /**
             * Efficient for 3+ strings
             * More efficient than multiple hashString calls IF strings are same length.
             */
            HashedString[] hashString(String... strings) {
                HashedString[] array = new HashedString[strings.length];
                int n = strings[0].length();
                long[] modifiers = new long[n];
                modifiers[0] = 1;
                for (int j=0; j<strings.length; j++) {
                    // if all strings are not same length, defer work to another method
                    if (strings[j].length() != n) {
                        for (int i=0; i<n; i++) {
                            array[i] = hashString(strings[i]);
                        }
                        return array;
                    }

                    // otherwise initialize stuff
                    long[] hashes = new long[n];
                    hashes[0] = strings[j].charAt(0);
                    array[j] = new HashedString(hashes, modifiers);
                }
                for (int i=1; i<n; i++) {
                    modifiers[i] = (modifiers[i-1] * P) % M;
                    for (int j=0; j<strings.length; j++) {
                        String s = strings[j];
                        long[] hashes = array[j].hashes;
                        hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
                    }
                }
                return array;
            }

            void initializePandM() {
                ArrayList<Long> modOptions = new ArrayList<>(20);
                modOptions.add(353873237L);
                modOptions.add(353875897L);
                modOptions.add(353878703L);
                modOptions.add(353882671L);
                modOptions.add(353885303L);
                modOptions.add(353888377L);
                modOptions.add(353893457L);
                P = modOptions.get(new Random().nextInt(modOptions.size()));

                modOptions.clear();
                modOptions.add(452940277L);
                modOptions.add(452947687L);
                modOptions.add(464478431L);
                modOptions.add(468098221L);
                modOptions.add(470374601L);
                modOptions.add(472879717L);
                modOptions.add(472881973L);
                M = modOptions.get(new Random().nextInt(modOptions.size()));

            }
        }

        private static class Prob {

            /** For heavy calculations on probabilities, this class
             *  provides more accuracy & efficiency than doubles.
             *  Math explained: https://en.wikipedia.org/wiki/Log_probability
             *  Quick start:
             *      - Instantiate probabilities, eg. Prob a = new Prob(0.75)
             *      - add(), multiply() return new objects, can perform on nulls & NaNs.
             *      - get() returns probability as a readable double */

            /** Logarithmized probability. Note: 0% represented by logP NaN. */
            private double logP;

            /** Construct instance with real probability. */
            public Prob(double real) {
                if (real > 0) this.logP = Math.log(real);
                else this.logP = Double.NaN;
            }

            /** Construct instance with already logarithmized value. */
            static boolean dontLogAgain = true;
            public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
                this.logP = logP;
            }

            /** Returns real probability as a double. */
            public double get() {
                return Math.exp(logP);
            }

            @Override
            public String toString() {
                return ""+get();
            }

            /***************** STATIC METHODS BELOW ********************/

            /** Note: returns NaN only when a && b are both NaN/null. */
            public static Prob add(Prob a, Prob b) {
                if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
                if (nullOrNaN(a)) return copy(b);
                if (nullOrNaN(b)) return copy(a);

                double x = a.logP;
                double y = b.logP;
                double sum = x + Math.log(1 + Math.exp(y - x));
                return new Prob(sum, dontLogAgain);
            }

            /** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
            public static Prob multiply(Prob a, Prob b) {
                if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
                return new Prob(a.logP + b.logP, dontLogAgain);
            }

            /** Returns true if p is null or NaN. */
            private static boolean nullOrNaN(Prob p) {
                return (p == null || Double.isNaN(p.logP));
            }

            /** Returns a new instance with the same value as original. */
            private static Prob copy(Prob original) {
                return new Prob(original.logP, dontLogAgain);
            }
        }

        public class StronglyConnectedComponents {

            /** Kosaraju's algorithm */

            ArrayList<Integer>[] forw;
            ArrayList<Integer>[] bacw;

            /** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */
            public int getCount(int n, int[] mista, int[] minne) {
                forw = new ArrayList[n+1];
                bacw = new ArrayList[n+1];
                for (int i=1; i<=n; i++) {
                    forw[i] = new ArrayList<Integer>();
                    bacw[i] = new ArrayList<Integer>();
                }
                for (int i=0; i<mista.length; i++) {
                    int a = mista[i];
                    int b = minne[i];
                    forw[a].add(b);
                    bacw[b].add(a);
                }
                int count = 0;
                List<Integer> list = new ArrayList<Integer>();
                boolean[] visited = new boolean[n+1];
                for (int i=1; i<=n; i++) {
                    dfsForward(i, visited, list);
                }
                visited = new boolean[n+1];
                for (int i=n-1; i>=0; i--) {
                    int node = list.get(i);
                    if (visited[node]) continue;
                    count++;
                    dfsBackward(node, visited);
                }
                return count;
            }

            public void dfsForward(int i, boolean[] visited, List<Integer> list) {
                if (visited[i]) return;
                visited[i] = true;
                for (int neighbor : forw[i]) {
                    dfsForward(neighbor, visited, list);
                }
                list.add(i);
            }

            public void dfsBackward(int i, boolean[] visited) {
                if (visited[i]) return;
                visited[i] = true;
                for (int neighbor : bacw[i]) {
                    dfsBackward(neighbor, visited);
                }
            }
        }

        class DrawGrid {

            void draw(boolean[][] d) {
                System.out.print("  ");
                for (int x=0; x<d[0].length; x++) {
                    System.out.print(" " + x + " ");
                }
                System.out.println("");
                for (int y=0; y<d.length; y++) {
                    System.out.print(y + " ");
                    for (int x=0; x<d[0].length; x++) {
                        System.out.print((d[y][x] ? "[x]" : "[ ]"));
                    }
                    System.out.println("");
                }
            }

            void draw(int[][] d) {
                int max = 1;
                for (int y=0; y<d.length; y++) {
                    for (int x=0; x<d[0].length; x++) {
                        max = Math.max(max, ("" + d[y][x]).length());
                    }
                }
                System.out.print("  ");
                String format = "%" + (max+2) + "s";
                for (int x=0; x<d[0].length; x++) {
                    System.out.print(String.format(format, x) + " ");
                }
                format = "%" + (max) + "s";
                System.out.println("");
                for (int y=0; y<d.length; y++) {
                    System.out.print(y + " ");
                    for (int x=0; x<d[0].length; x++) {
                        System.out.print(" [" + String.format(format, (d[y][x])) + "]");
                    }
                    System.out.println("");
                }
            }

        }

        class BaseConverter {

            /* Palauttaa luvun esityksen kannassa base */
            public String convert(Long number, int base) {
                return Long.toString(number, base);
            }

            /* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */
            public String convert(String number, int baseFrom, int baseTo) {
                return Long.toString(Long.parseLong(number, baseFrom), baseTo);
            }

            /* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
            public long longify(String number, int baseFrom) {
                return Long.parseLong(number, baseFrom);
            }
        }

        class Binary implements Comparable<Binary> {

            /**
             * Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
             *
             * When manipulating small binary strings, instantiate new Binary(string)
             * When just reading large binary strings, instantiate new Binary(string,true)
             * get(int i) returns a character '1' or '0', not an int.
             */

            private boolean[] d;
            private int first; // Starting from left, the first (most remarkable) '1'
            public int length;

            public Binary(String binaryString) {
                this(binaryString, false);
            }
            public Binary(String binaryString, boolean initWithMinArraySize) {
                length = binaryString.length();
                int size = Math.max(2*length, 1);
                first = length/4;
                if (initWithMinArraySize) {
                    first = 0;
                    size = Math.max(length, 1);
                }
                d = new boolean[size];
                for (int i=0; i<length; i++) {
                    if (binaryString.charAt(i) == '1') d[i+first] = true;
                }
            }

            public void addFirst(char c) {
                if (first-1 < 0) doubleArraySize();
                first--;
                d[first] = (c == '1' ? true : false);
                length++;
            }

            public void addLast(char c) {
                if (first+length >= d.length) doubleArraySize();
                d[first+length] = (c == '1' ? true : false);
                length++;
            }

            private void doubleArraySize() {
                boolean[] bigArray = new boolean[(d.length+1) * 2];
                int newFirst = bigArray.length / 4;
                for (int i=0; i<length; i++) {
                    bigArray[i + newFirst] = d[i + first];
                }
                first = newFirst;
                d = bigArray;
            }

            public boolean flip(int i) {
                boolean value = (this.d[first+i] ? false : true);
                this.d[first+i] = value;
                return value;
            }

            public void set(int i, char c) {
                boolean value = (c == '1' ? true : false);
                this.d[first+i] = value;
            }

            public char get(int i) {
                return (this.d[first+i] ? '1' : '0');
            }

            @Override
            public int compareTo(Binary o) {
                if (this.length != o.length) return this.length - o.length;
                int len = this.length;
                for (int i=0; i<len; i++) {
                    int diff = this.get(i) - o.get(i);
                    if (diff != 0) return diff;
                }
                return 0;
            }

            @Override
            public String toString() {
                StringBuilder sb = new StringBuilder();
                for (int i=0; i<length; i++) {
                    sb.append(d[i+first] ? '1' : '0');
                }
                return sb.toString();
            }

        }

        class BinomialCoefficients {
            /** Total number of K sized unique combinations from pool of size N (unordered)
             N! / ( K! (N - K)! )   */

            /** For simple queries where output fits in long. */
            public long biCo(long n, long k) {
                long r = 1;
                if (k > n) return 0;
                for (long d = 1; d <= k; d++) {
                    r *= n--;
                    r /= d;
                }
                return r;
            }

            /** For multiple queries with same n, different k. */
            public long[] precalcBinomialCoefficientsK(int n, int maxK) {
                long v[] = new long[maxK+1];
                v[0] = 1; // nC0 == 1
                for (int i=1; i<=n; i++) {
                    for (int j=Math.min(i,maxK); j>0; j--) {
                        v[j] = v[j] + v[j-1]; // Pascal's triangle
                    }
                }
                return v;
            }

            /** When output needs % MOD. */
            public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
                long v[] = new long[k+1];
                v[0] = 1; // nC0 == 1
                for (int i=1; i<=n; i++) {
                    for (int j=Math.min(i,k); j>0; j--) {
                        v[j] = v[j] + v[j-1]; // Pascal's triangle
                        v[j] %= M;
                    }
                }
                return v;
            }
        }

        class GreatestCommonDivisor {

            /** Chained calls to Euclidean algorithm. */
            long gcd(long... v) {
                if (v.length == 1) return v[0];
                long ans = gcd(v[1], v[0]);
                for (int i=2; i<v.length; i++) {
                    ans = gcd(ans, v[i]);
                }
                return ans;
            }

            /** Euclidean algorithm. */
            long gcd(long a, long b) {
                if (b == 0) return a;
                return gcd(b, a%b);
            }
        }

        private class IO extends PrintWriter {
            private InputStreamReader r;
            private static final int BUFSIZE = 1 << 15;
            private char[] buf;
            private int bufc;
            private int bufi;
            private StringBuilder sb;

            public IO() {
                super(new BufferedOutputStream(System.out));
                r = new InputStreamReader(System.in);

                buf = new char[BUFSIZE];
                bufc = 0;
                bufi = 0;
                sb = new StringBuilder();
            }

            private void fillBuf() throws IOException {
                bufi = 0;
                bufc = 0;
                while(bufc == 0) {
                    bufc = r.read(buf, 0, BUFSIZE);
                    if(bufc == -1) {
                        bufc = 0;
                        return;
                    }
                }
            }

            private boolean pumpBuf() throws IOException {
                if(bufi == bufc) {
                    fillBuf();
                }
                return bufc != 0;
            }

            private boolean isDelimiter(char c) {
                return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
            }

            private void eatDelimiters() throws IOException {
                while(true) {
                    if(bufi == bufc) {
                        fillBuf();
                        if(bufc == 0) throw new RuntimeException("IO: Out of input.");
                    }

                    if(!isDelimiter(buf[bufi])) break;
                    ++bufi;
                }
            }

            public String next() {
                try {
                    sb.setLength(0);

                    eatDelimiters();
                    int start = bufi;

                    while(true) {
                        if(bufi == bufc) {
                            sb.append(buf, start, bufi - start);
                            fillBuf();
                            start = 0;
                            if(bufc == 0) break;
                        }

                        if(isDelimiter(buf[bufi])) break;
                        ++bufi;
                    }

                    sb.append(buf, start, bufi - start);

                    return sb.toString();
                } catch(IOException e) {
                    throw new RuntimeException("IO.next: Caught IOException.");
                }
            }

            public int nextInt() {
                try {
                    int ret = 0;

                    eatDelimiters();

                    boolean positive = true;
                    if(buf[bufi] == '-') {
                        ++bufi;
                        if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
                        positive = false;
                    }

                    boolean first = true;
                    while(true) {
                        if(!pumpBuf()) break;
                        if(isDelimiter(buf[bufi])) {
                            if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
                            break;
                        }
                        first = false;

                        if(buf[bufi] >= '0' && buf[bufi] <= '9') {
                            if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
                            ret *= 10;
                            ret -= (int)(buf[bufi] - '0');
                            if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
                        } else {
                            throw new RuntimeException("IO.nextInt: Invalid int.");
                        }

                        ++bufi;
                    }

                    if(positive) {
                        if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
                        ret = -ret;
                    }

                    return ret;
                } catch(IOException e) {
                    throw new RuntimeException("IO.nextInt: Caught IOException.");
                }
            }

            public long nextLong() {
                try {
                    long ret = 0;

                    eatDelimiters();

                    boolean positive = true;
                    if(buf[bufi] == '-') {
                        ++bufi;
                        if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
                        positive = false;
                    }

                    boolean first = true;
                    while(true) {
                        if(!pumpBuf()) break;
                        if(isDelimiter(buf[bufi])) {
                            if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
                            break;
                        }
                        first = false;

                        if(buf[bufi] >= '0' && buf[bufi] <= '9') {
                            if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
                            ret *= 10;
                            ret -= (long)(buf[bufi] - '0');
                            if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
                        } else {
                            throw new RuntimeException("IO.nextLong: Invalid long.");
                        }

                        ++bufi;
                    }

                    if(positive) {
                        if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
                        ret = -ret;
                    }

                    return ret;
                } catch(IOException e) {
                    throw new RuntimeException("IO.nextLong: Caught IOException.");
                }
            }

            public double nextDouble() {
                return Double.parseDouble(next());
            }

        }
    }

}

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class problem
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);
     	int n = sc.nextInt();
     	int crush[] = new int[n];
        int next_crush[] = new int[n];
     	int flag = 0;

        for(int i=1;i<=n;i++){
     		crush[i-1] = sc.nextInt();
            next_crush[i-1] = crush[i-1];
        }

        for(int t=1; t <= 2*n ; t++){
            int counter = 0;
            for(int j=1;j<=n;j++){
                if(next_crush[j-1] == j)
                    counter++;
                next_crush[j-1] = crush[next_crush[j-1]-1];
            }
            if(counter == n && t%2 == 0){
                System.out.println(t/2);
                flag =1;
                break;
            }
        }
        if(flag == 0)
            System.out.println("-1");
	}

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int N = in.nextInt();
            int[] next = new int[N];
            for (int i = 0; i < N; i++) {
                next[i] = in.nextInt() - 1;
            }
            iter:
            for (int t = 1; t <= 2000; t++) {
                int[] match = new int[N];
                for (int j = 0; j < N; j++) {
                    int tempT = t;
                    int cur = j;
                    while (tempT-- > 0) {
                        cur = next[cur];
                    }
                    match[j] = cur;
                }
                for (int j = 0; j < N; j++) {
                    if (j != match[match[j]]) {
                        continue iter;
                    }
                }
                out.println(t);
                return;
            }
            out.println(-1);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int N = in.nextInt();
            int[] next = new int[N];
            for (int i = 0; i < N; i++) {
                next[i] = in.nextInt() - 1;
            }
            int[] match = new int[N];
            for (int i = 0; i < N; i++) {
                match[i] = i;
            }
            iter:
            for (int t = 1; t <= 10000; t++) {
                for (int j = 0; j < N; j++) {
                    match[j] = next[match[j]];
                }
                for (int j = 0; j < N; j++) {
                    if (j != match[match[j]]) {
                        continue iter;
                    }
                }
                out.println(t);
                return;
            }
            out.println(-1);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.Random;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.NoSuchElementException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n;
            int[] crush;

            n = in.readInt();
            crush = IOUtils.readIntArray(in, n);
            MiscUtils.decreaseByOne(crush);

            IntArrayList sizes = new IntArrayList();

            for (int i = 0; i < n; i++) {
                IntArrayList arr = new IntArrayList();
                IntSet set = new IntHashSet();
                for (int v = i; ; ) {
                    if (set.contains(v)) {
                        if (v == i) {
                            sizes.add(arr.size());
                            break;
                        } else {
                            out.printLine("-1");
                            return;
                        }
                    } else {
                        set.add(v);
                        arr.add(v);
                        v = crush[v];
                    }
                }
            }
            Sorter.sort(sizes, IntComparator.DEFAULT);

            cyc:
            for (int maxSize : new int[]{sizes.last() / 2, sizes.last()}) {
                for (int sz : sizes) {
                    if (!(maxSize % sz == 0 || sz % 2 == 0 && (maxSize - sz / 2) % sz == 0)) {
                        continue cyc;
                    }
                }
                out.printLine(maxSize);
                return;
            }
            out.printLine("-1");
        }

    }

    static class IOUtils {
        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.readInt();
            }
            return array;
        }

    }

    static interface IntCollection extends IntStream {
        public int size();

        default public void add(int value) {
            throw new UnsupportedOperationException();
        }

        default public IntCollection addAll(IntStream values) {
            for (IntIterator it = values.intIterator(); it.isValid(); it.advance()) {
                add(it.value());
            }
            return this;
        }

    }

    static class Sorter {
        private static final int INSERTION_THRESHOLD = 16;

        private Sorter() {
        }

        public static void sort(IntList list, IntComparator comparator) {
            quickSort(list, 0, list.size() - 1, (Integer.bitCount(Integer.highestOneBit(list.size()) - 1) * 5) >> 1,
                    comparator);
        }

        private static void quickSort(IntList list, int from, int to, int remaining, IntComparator comparator) {
            if ((to - from) < INSERTION_THRESHOLD) {
                insertionSort(list, from, to, comparator);
                return;
            }
            if (remaining == 0) {
                heapSort(list, from, to, comparator);
                return;
            }
            remaining--;
            int pivotIndex = (from + to) >> 1;
            int pivot = list.get(pivotIndex);
            list.swap(pivotIndex, to);
            int storeIndex = from;
            int equalIndex = to;
            for (int i = from; i < equalIndex; i++) {
                int value = comparator.compare(list.get(i), pivot);
                if (value < 0) {
                    list.swap(storeIndex++, i);
                } else if (value == 0) {
                    list.swap(--equalIndex, i--);
                }
            }
            quickSort(list, from, storeIndex - 1, remaining, comparator);
            for (int i = equalIndex; i <= to; i++) {
                list.swap(storeIndex++, i);
            }
            quickSort(list, storeIndex, to, remaining, comparator);
        }

        private static void heapSort(IntList list, int from, int to, IntComparator comparator) {
            for (int i = ((to + from) - 1) >> 1; i >= from; i--) {
                siftDown(list, i, to, comparator, from);
            }
            for (int i = to; i > from; i--) {
                list.swap(from, i);
                siftDown(list, from, i - 1, comparator, from);
            }
        }

        private static void siftDown(IntList list, int start, int end, IntComparator comparator, int delta) {
            int value = list.get(start);
            while (true) {
                int child = ((start - delta) << 1) + 1 + delta;
                if (child > end) {
                    return;
                }
                int childValue = list.get(child);
                if ((child + 1) <= end) {
                    int otherValue = list.get(child + 1);
                    if (comparator.compare(otherValue, childValue) > 0) {
                        child++;
                        childValue = otherValue;
                    }
                }
                if (comparator.compare(value, childValue) >= 0) {
                    return;
                }
                list.swap(start, child);
                start = child;
            }
        }

        private static void insertionSort(IntList list, int from, int to, IntComparator comparator) {
            for (int i = from + 1; i <= to; i++) {
                int value = list.get(i);
                for (int j = i - 1; j >= from; j--) {
                    if (comparator.compare(list.get(j), value) <= 0) {
                        break;
                    }
                    list.swap(j, j + 1);
                }
            }
        }

    }

    static class MiscUtils {
        public static void decreaseByOne(int[]... arrays) {
            for (int[] array : arrays) {
                for (int i = 0; i < array.length; i++) {
                    array[i]--;
                }
            }
        }

    }

    static interface IntIterator {
        public int value() throws NoSuchElementException;

        public boolean advance();

        public boolean isValid();

    }

    static class IntHashSet extends IntAbstractStream implements IntSet {
        private static final Random RND = new Random();
        private static final int[] SHIFTS = new int[4];
        private static final byte PRESENT_MASK = 1;
        private static final byte REMOVED_MASK = 2;
        private int size;
        private int realSize;
        private int[] values;
        private byte[] present;
        private int step;
        private int ratio;

        static {
            for (int i = 0; i < 4; i++) {
                SHIFTS[i] = RND.nextInt(31) + 1;
            }
        }

        public IntHashSet() {
            this(3);
        }

        public IntHashSet(int capacity) {
            capacity = Math.max(capacity, 3);
            values = new int[capacity];
            present = new byte[capacity];
            ratio = 2;
            initStep(capacity);
        }

        public IntHashSet(IntCollection c) {
            this(c.size());
            addAll(c);
        }

        public IntHashSet(int[] arr) {
            this(new IntArray(arr));
        }

        private void initStep(int capacity) {
            step = RND.nextInt(capacity - 2) + 1;
            while (IntegerUtils.gcd(step, capacity) != 1) {
                step++;
            }
        }

        public IntIterator intIterator() {
            return new IntIterator() {
                private int position = (size == 0) ? values.length : -1;

                public int value() throws NoSuchElementException {
                    if (position == -1) {
                        advance();
                    }
                    if (position >= values.length) {
                        throw new NoSuchElementException();
                    }
                    if ((present[position] & PRESENT_MASK) == 0) {
                        throw new IllegalStateException();
                    }
                    return values[position];
                }

                public boolean advance() throws NoSuchElementException {
                    if (position >= values.length) {
                        throw new NoSuchElementException();
                    }
                    position++;
                    while ((position < values.length) && ((present[position] & PRESENT_MASK) == 0)) {
                        position++;
                    }
                    return isValid();
                }

                public boolean isValid() {
                    return position < values.length;
                }

                public void remove() {
                    if ((present[position] & PRESENT_MASK) == 0) {
                        throw new IllegalStateException();
                    }
                    present[position] = REMOVED_MASK;
                }
            };
        }

        public int size() {
            return size;
        }

        public void add(int value) {
            ensureCapacity(((realSize + 1) * ratio) + 2);
            int current = getHash(value);
            while (present[current] != 0) {
                if (((present[current] & PRESENT_MASK) != 0) && (values[current] == value)) {
                    return;
                }
                current += step;
                if (current >= values.length) {
                    current -= values.length;
                }
            }
            while ((present[current] & PRESENT_MASK) != 0) {
                current += step;
                if (current >= values.length) {
                    current -= values.length;
                }
            }
            if (present[current] == 0) {
                realSize++;
            }
            present[current] = PRESENT_MASK;
            values[current] = value;
            size++;
        }

        private int getHash(int value) {
            int hash = IntHash.hash(value);
            int result = hash;
            for (int i : SHIFTS) {
                result ^= hash >> i;
            }
            result %= values.length;
            if (result < 0) {
                result += values.length;
            }
            return result;
        }

        private void ensureCapacity(int capacity) {
            if (values.length < capacity) {
                capacity = Math.max(capacity * 2, values.length);
                rebuild(capacity);
            }
        }

        private void rebuild(int capacity) {
            initStep(capacity);
            int[] oldValues = values;
            byte[] oldPresent = present;
            values = new int[capacity];
            present = new byte[capacity];
            size = 0;
            realSize = 0;
            for (int i = 0; i < oldValues.length; i++) {
                if ((oldPresent[i] & PRESENT_MASK) == PRESENT_MASK) {
                    add(oldValues[i]);
                }
            }
        }

        public boolean contains(int value) {
            int current = getHash(value);
            while (present[current] != 0) {
                if ((values[current] == value) && ((present[current] & PRESENT_MASK) != 0)) {
                    return true;
                }
                current += step;
                if (current >= values.length) {
                    current -= values.length;
                }
            }
            return false;
        }

    }

    static class IntegerUtils {
        public static int gcd(int a, int b) {
            a = Math.abs(a);
            b = Math.abs(b);
            while (b != 0) {
                int temp = a % b;
                a = b;
                b = temp;
            }
            return a;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

        public void printLine(int i) {
            writer.println(i);
        }

    }

    static class IntHash {
        private IntHash() {
        }

        public static int hash(int c) {
            return c;
        }

    }

    static class IntArrayList extends IntAbstractStream implements IntList {
        private int size;
        private int[] data;

        public IntArrayList() {
            this(3);
        }

        public IntArrayList(int capacity) {
            data = new int[capacity];
        }

        public IntArrayList(IntCollection c) {
            this(c.size());
            addAll(c);
        }

        public IntArrayList(IntStream c) {
            this();
            if (c instanceof IntCollection) {
                ensureCapacity(((IntCollection) c).size());
            }
            addAll(c);
        }

        public IntArrayList(IntArrayList c) {
            size = c.size();
            data = c.data.clone();
        }

        public IntArrayList(int[] arr) {
            size = arr.length;
            data = arr.clone();
        }

        public int size() {
            return size;
        }

        public int get(int at) {
            if (at >= size) {
                throw new IndexOutOfBoundsException("at = " + at + ", size = " + size);
            }
            return data[at];
        }

        private void ensureCapacity(int capacity) {
            if (data.length >= capacity) {
                return;
            }
            capacity = Math.max(2 * data.length, capacity);
            data = Arrays.copyOf(data, capacity);
        }

        public void addAt(int index, int value) {
            ensureCapacity(size + 1);
            if ((index > size) || (index < 0)) {
                throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
            }
            if (index != size) {
                System.arraycopy(data, index, data, index + 1, size - index);
            }
            data[index] = value;
            size++;
        }

        public void removeAt(int index) {
            if ((index >= size) || (index < 0)) {
                throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
            }
            if (index != (size - 1)) {
                System.arraycopy(data, index + 1, data, index, size - index - 1);
            }
            size--;
        }

        public void set(int index, int value) {
            if (index >= size) {
                throw new IndexOutOfBoundsException("at = " + index + ", size = " + size);
            }
            data[index] = value;
        }

    }

    static interface IntList extends IntReversableCollection {
        public abstract int get(int index);

        public abstract void set(int index, int value);

        public abstract void addAt(int index, int value);

        public abstract void removeAt(int index);

        default public int last() {
            return get(size() - 1);
        }

        default public void swap(int first, int second) {
            if (first == second) {
                return;
            }
            int temp = get(first);
            set(first, get(second));
            set(second, temp);
        }

        default public IntIterator intIterator() {
            return new IntIterator() {
                private int at;
                private boolean removed;

                public int value() {
                    if (removed) {
                        throw new IllegalStateException();
                    }
                    return get(at);
                }

                public boolean advance() {
                    at++;
                    removed = false;
                    return isValid();
                }

                public boolean isValid() {
                    return !removed && (at < size());
                }

                public void remove() {
                    removeAt(at);
                    at--;
                    removed = true;
                }
            };
        }

        default public void add(int value) {
            addAt(size(), value);
        }

    }

    static interface IntReversableCollection extends IntCollection {
    }

    static abstract class IntAbstractStream implements IntStream {

        public String toString() {
            StringBuilder builder = new StringBuilder();
            boolean first = true;
            for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
                if (first) {
                    first = false;
                } else {
                    builder.append(' ');
                }
                builder.append(it.value());
            }
            return builder.toString();
        }

        public boolean equals(Object o) {
            if (!(o instanceof IntStream)) {
                return false;
            }
            IntStream c = (IntStream) o;
            IntIterator it = intIterator();
            IntIterator jt = c.intIterator();
            while (it.isValid() && jt.isValid()) {
                if (it.value() != jt.value()) {
                    return false;
                }
                it.advance();
                jt.advance();
            }
            return !it.isValid() && !jt.isValid();
        }

        public int hashCode() {
            int result = 0;
            for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
                result *= 31;
                result += it.value();
            }
            return result;
        }

    }

    static interface IntComparator {
        public static final IntComparator DEFAULT = (first, second) -> {
            if (first < second) {
                return -1;
            }
            if (first > second) {
                return 1;
            }
            return 0;
        };

        public int compare(int first, int second);

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if ((c < '0') || (c > '9')) {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return (c == ' ') || (c == '\n') || (c == '\r') || (c == '\t') || (c == -1);
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class IntArray extends IntAbstractStream implements IntList {
        private int[] data;

        public IntArray(int[] arr) {
            data = arr;
        }

        public int size() {
            return data.length;
        }

        public int get(int at) {
            return data[at];
        }

        public void addAt(int index, int value) {
            throw new UnsupportedOperationException();
        }

        public void removeAt(int index) {
            throw new UnsupportedOperationException();
        }

        public void set(int index, int value) {
            data[index] = value;
        }

    }

    static interface IntStream extends Iterable<Integer>, Comparable<IntStream> {
        public IntIterator intIterator();

        default public Iterator<Integer> iterator() {
            return new Iterator<Integer>() {
                private IntIterator it = intIterator();

                public boolean hasNext() {
                    return it.isValid();
                }

                public Integer next() {
                    int result = it.value();
                    it.advance();
                    return result;
                }
            };
        }

        default public int compareTo(IntStream c) {
            IntIterator it = intIterator();
            IntIterator jt = c.intIterator();
            while (it.isValid() && jt.isValid()) {
                int i = it.value();
                int j = jt.value();
                if (i < j) {
                    return -1;
                } else if (i > j) {
                    return 1;
                }
                it.advance();
                jt.advance();
            }
            if (it.isValid()) {
                return 1;
            }
            if (jt.isValid()) {
                return -1;
            }
            return 0;
        }

        default public boolean contains(int value) {
            for (IntIterator it = intIterator(); it.isValid(); it.advance()) {
                if (it.value() == value) {
                    return true;
                }
            }
            return false;
        }

    }

    static interface IntSet extends IntCollection {
    }
}

//package que_a;

import java.io.*;
import java.util.*;
import java.math.*;

public class utkarsh {

    InputStream is;
    PrintWriter out;

    long mod = (long) (1e9 + 7), inf = (long) (8e18);
    boolean SHOW_TIME, debug;

    void solve() {
        //Enter code here utkarsh
        //SHOW_TIME = true;
	//debug = true;
        int n = ni();
        int a[] = new int[n];
        for(int i = 0; i < n; i++)  a[i] = ni() - 1;
        int dp[][] = new int[n][n];
        for(int i = 0; i < n; i++) {
            int x = a[i];
            for(int j = 0; j < n; j++) {
                dp[i][j] = x;   x = a[x];
            }
        }
        int ans = -1;
        for(int i = 0; i < n; i++) {
            boolean f = true;
            for(int j = 0; j < n; j++) {
                int x = dp[j][i];
                if(dp[x][i] != j) {
                    f = false;  break;
                }
            }
            if(f) {
                ans = i+1;  break;
            }
        }
        out.println(ans);
    }

    long X, Y;  // X = a^-1 % b
    long gcd(long a, long b) {
        if(b == 0) {
            X = 1;  Y = 0;  return a;
        } else {
            long d = gcd(b, a % b);
            long t = X;
            X = Y;
            Y = t - (a / b) * Y;
            return d;
        }
    }

    long mp(long b, long e) {
        long r = 1;
        while(e > 0) {
            if((e&1) == 1)  r = (r * b) % mod;
            b = (b * b) % mod;
            e >>= 1;
        }
        return r;
    }

    //---------- I/O Template ----------

    public static void main(String[] args) { new utkarsh().run(); }
    void run() {
        is = System.in;
        out = new PrintWriter(System.out);
        long start = System.currentTimeMillis();
        solve();
        long end = System.currentTimeMillis();
        if(SHOW_TIME) out.println("\n" + (end - start) + " ms");
        out.flush();
    }

    byte input[] = new byte[1024];
    int len = 0, ptr = 0;

    int readByte() {
        if(ptr >= len) { ptr = 0;
            try { len = is.read(input); }
            catch(IOException e) { throw new InputMismatchException(); }
            if(len <= 0) { return -1; }
        } return input[ptr++];
    }
    boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); }
    int skip() {
        int b = readByte();
        while(b != -1 && isSpaceChar(b)) { b = readByte(); }
        return b;
    }

    char nc() { return (char)skip(); }
    String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); }
        return sb.toString();
    }
    String nLine() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); }
        return sb.toString();
    }
    int ni() {
        int n = 0, b = readByte();
        boolean minus = false;
        while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
        if(b == '-') { minus = true; b = readByte(); }
        if(b == -1) { return -1; }  //no input
        while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
        return minus ? -n : n;
    }
    long nl() {
        long n = 0L;    int b = readByte();
        boolean minus = false;
        while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
        if(b == '-') { minus = true; b = readByte(); }
        while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
        return minus ? -n : n;
    }

    double nd() { return Double.parseDouble(ns()); }
    float nf() { return Float.parseFloat(ns()); }
    int[] na(int n) {
        int a[] = new int[n];
        for(int i = 0; i < n; i++) { a[i] = ni(); }
        return a;
    }
    char[] ns(int n) {
        char c[] = new char[n];
        int i, b = skip();
        for(i = 0; i < n; i++) {
            if(isSpaceChar(b)) { break; }
            c[i] = (char)b; b = readByte();
        } return i == n ? c : Arrays.copyOf(c,i);
    }
}

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Objects;
import java.util.StringTokenizer;

public final class Main {
    static char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    static char[] chars1 = {'#', '*', '&'};
    static char[] chars2 = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};

    static boolean oneColor = true;

    // x1<0
    // x1+k*2>0;
    // k*2>-x1;
    // k=-x1/2
    public void solve() {
        int n = in.nextInt();
        int[] crush = new int[100];
        for (int i = 0; i < n; i++) {
            crush[i] = in.nextInt() - 1;
        }
        ArrayList<Integer> al = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int tmp = crush[i];
            int t = 1;
            while (tmp != i && t <= n) {
                int tmpp = tmp;
                tmp = crush[tmp];
                if (tmpp == tmp) {
                    out.println(-1);
                    return;
                }
                t++;
            }
            if (t > n) {
                out.println(-1);
                return;
            }
            if (t % 2 == 0) {
                al.add(t / 2);
            } else {
                al.add(t);
            }
        }
        long lcm = al.get(0);
        for (int i=0; i<al.size();i++){
            lcm=Library.lcm(lcm,al.get(0));
        }
        out.println(lcm);
    }

    static class Library {
        static boolean isPrime(int a) {
            if (a == 1) {
                return false;
            }
            for (int i = 2; i * i <= a; i++) {
                if (a % i == 0)
                    return false;
            }
            return true;
        }

        static long bpow(long x, long n, long m) {
            long count = 1;
            if (n == 0) {
                return 1;
            }
            while (n > 0) {
                if ((n & 1) == 1) {
                    count *= x;
                    count %= m;
                }
                x *= x;
                x %= m;
                n >>= 1;
            }
            return count % m;
        }

        static long GCD(long a, long b) {
            if (b == 0) return a;
            return GCD(b, a % b);
        }

        static long lcm(long a, long b) {
            return (a * b) / Library.GCD(a, b);
        }
    }

    class Pair<X, Y> implements Comparable<Pair<X, Y>> {

        public X first;
        public Y second;

        public Pair(X first, Y second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public int hashCode() {
            int hash = 7;
            hash = 11 * hash + Objects.hashCode(this.first);
            hash = 11 * hash + Objects.hashCode(this.second);
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Pair<?, ?> other = (Pair<?, ?>) obj;
            if (!Objects.equals(this.first, other.first)) {
                return false;
            }
            if (!Objects.equals(this.second, other.second)) {
                return false;
            }
            return true;
        }

        @Override
        public int compareTo(Pair<X, Y> p) {
            return ((Comparable<X>) first).compareTo(p.first);
        }

        @Override
        public String toString() {
            return first + " " + second;
        }
    }

    class Node<E> {
        E element;
        Node<E> next;
        Node<E> prev;

        Node(E element, Node next, Node prev) {
            this.element = element;
            this.next = next;
            this.prev = prev;
        }
    }

    //    -------------I/O-------------    \\
    private FScanner in;

    private PrintWriter out;

    public static void main(String[] args) {
        new Main().runIO();
    }

    void run() {
        try {
            in = new FScanner(new File("input.txt"));
            out = new PrintWriter(new BufferedWriter(new FileWriter(new File("output.txt"))));
            solve();
            out.close();
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    void runIO() {
        in = new FScanner();
        out = new PrintWriter(new BufferedOutputStream(System.out));
        solve();
        out.close();
        in.close();
    }

    class FScanner {

        private BufferedReader br;
        private StringTokenizer st;

        public FScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FScanner(File f) {
            try {
                br = new BufferedReader(new FileReader(f));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
        }

        void useString(String s) {
            if (s != null) {
                st = new StringTokenizer(s);
            }
        }

        void updateST() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String next() {
            updateST();
            return st.nextToken();
        }

        Long[] nextLongArray() {
            updateST();
            LinkedList<Long> ll = new LinkedList<>();
            while (st.hasMoreElements()) {
                ll.add(Long.parseLong(st.nextToken()));
            }
            Long[] arr = new Long[1];
            return ll.toArray(arr);
        }

        Integer[] nextIntArray() {
            updateST();
            LinkedList<Integer> ll = new LinkedList<>();
            while (st.hasMoreElements()) {
                ll.add(Integer.parseInt(st.nextToken()));
            }
            Integer[] arr = new Integer[1];
            return ll.toArray(arr);
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            updateST();
            StringBuilder sb = new StringBuilder(st.nextToken());
            while (st.hasMoreElements()) {
                sb.append(st.nextToken());
            }
            return sb.toString();
        }

        void close() {
            try {
                br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Random;
import java.util.StringTokenizer;

public class A {
    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
        FastScanner sc = new FastScanner();

        int n = sc.nextInt();
        int[] crush = new int[n];
        for (int i = 0; i < n; i++) {
            crush[i] = sc.nextInt() - 1;
        }

        outer:
        for (int t = 1; t <= n; t++) {
            for (int x = 0; x < n; x++) {
                int y = get(t, x, crush);
                int xx = get(t, y, crush);
                if (x != xx) {
                    continue outer;
                }
            }
            System.out.println(t);
            return;
        }

        System.out.println(-1);
    }

    static int get(int t, int cur, int[] crush) {
        if (t == 0) {
            return cur;
        }
        return get(t - 1, crush[cur], crush);
    }

    static void shuffle(int[] arr) {
        Random rng = new Random();
        int length = arr.length;
        for (int idx = 0; idx < arr.length; idx++) {
            int toSwap = idx + rng.nextInt(length-idx);
            int tmp = arr[idx];
            arr[idx] = arr[toSwap];
            arr[toSwap] = tmp;
        }
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;
        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }
        public FastScanner() {
            this(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }
        long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextLong();
            }
            return a;
        }
    }
}

import java.util.*;
import java.io.*;

public class Class{
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());
        int[] a = new int[n+1];
        for(int i=1; i<=n; i++)a[i] = Integer.parseInt(st.nextToken());
        int lcm = 1;
        long ans = 1;
        boolean[] b = new boolean[n+1];
        for(int i=1; i<=n; i++){
            if(!b[i]){
                int x = count(a, b, i);
                if(x==-1){System.out.print(-1); return;}
                ans = lcm(ans,x);
            }
        }
        System.out.print(ans);
    }
    public static int count(int[] a, boolean[] b, int i){
        int y = a[i]; int len = a.length;
        int count = 1; b[i] = true;
        while(y!=i){
            if(b[y]==true)return -1;
            b[y] = true;
            y = a[y];
            count++;
        }
        if(count%2==0)return count/2;
        else return count;
    }
    public static long lcm(long ans, long lcm){
        long hcf = hcf(ans, lcm);
        return (ans*lcm)/hcf;
    }
    public static long hcf(long ans, long lcm){
        if(ans>lcm){long temp = ans; ans = lcm; lcm = temp;}
        if(lcm%ans==0)return ans;
        return hcf(lcm, lcm%ans);
    }
}

import java.io.*;    //PrintWriter
import java.math.*;  //BigInteger, BigDecimal
import java.util.*;  //StringTokenizer, ArrayList

public class R383_Div2_C
{
	FastReader in;
	PrintWriter out;

	public static void main(String[] args)  {
		new R383_Div2_C().run();
	}

	void run()
	{
		in = new FastReader(System.in);
		out = new PrintWriter(System.out);
		solve();
		out.close();
	}

	void solve()
	{
		int n = in.nextInt();

		int[] a = new int[n+1];
		boolean[] used = new boolean[n+1];
		for (int i = 1; i <= n; i++)
			a[i] = in.nextInt();

		ArrayList<Integer> cycle = new ArrayList<>();
		int max = 0;
		long lcm = 1;
		for (int i = 1; i <= n; i++)
			if (!used[i])
			{
				used[i] = true;
				int cyc = 1;
				int nex = a[i];
				while (!used[nex])
				{
					used[nex] = true;
					nex = a[nex];
					cyc++;
				}
				if (i != nex)
				{
					lcm = -1;
					break;
				}
				cycle.add(cyc);
				if (cyc % 2 == 0) cyc /= 2;
				max = Math.max(max, cyc);
				lcm = LCM(max, lcm);
			}

		out.println(lcm);
	}

    long GCD(long a, long b)
    {
        if (b == 0) return a;
        return GCD(b, a % b);
    }
    long LCM(long a, long b)
    {
        return a * b / GCD(a, b);
    }

	//-----------------------------------------------------
	void runWithFiles() {
		in = new FastReader(new File("input.txt"));
		try {
			out = new PrintWriter(new File("output.txt"));
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		solve();
		out.close();
	}

	class FastReader
	{
	    BufferedReader br;
	    StringTokenizer tokenizer;

	    public FastReader(InputStream stream)
	    {
	        br = new BufferedReader(new InputStreamReader(stream));
	        tokenizer = null;
	    }
		public FastReader(File f) {
			try {
				br = new BufferedReader(new FileReader(f));
				tokenizer = null;
			}
			catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

	    private String next() {
	        while (tokenizer == null || !tokenizer.hasMoreTokens())
	            try {
	            	tokenizer = new StringTokenizer(br.readLine());
	            }
	            catch (IOException e) {
	                throw new RuntimeException(e);
	            }
	        return tokenizer.nextToken();
	    }
		public String nextLine() {
			try	{
				return br.readLine();
			}
			catch(Exception e) {
				throw(new RuntimeException());
			}
		}

	    int nextInt() {
	        return Integer.parseInt(next());
	    }
	    long nextLong() {
	        return Long.parseLong(next());
	    }
	    double nextDouble() {
	        return Double.parseDouble(next());
	    }
	    BigInteger nextBigInteger() {
	        return new BigInteger(next());
	    }
	    BigDecimal nextBigDecimal() {
	        return new BigDecimal(next());
	    }
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class C {

	static class Scanner{
		BufferedReader br=null;
		StringTokenizer tk=null;
		public Scanner(){
			br=new BufferedReader(new InputStreamReader(System.in));
		}
		public String next() throws IOException{
			while(tk==null || !tk.hasMoreTokens()) {
				String cad = br.readLine();
				if (cad == null)
					return null;
				tk=new StringTokenizer(cad);
			}
			return tk.nextToken();
		}
		public int nextInt() throws NumberFormatException, IOException{
			return Integer.valueOf(next());
		}
		public long nextLong() throws NumberFormatException, IOException{
			return Long.valueOf(next());
		}
		public double nextDouble() throws NumberFormatException, IOException{
			return Double.valueOf(next());
		}
	}

	static int N;
	static int[] array;
	static boolean[] visited;

	static int find(int index, int first, int count) {
		if (visited[index])
			return -1;
		visited[index] = true;
		if (count == N && index != first)
			return -1;
		if (index == first)
			return count;
		return find(array[index], first, count + 1);
	}

	static boolean test(int number, TreeSet<Integer> set) {
		for(int e: set) {
			int r = number % e;
			if (!(r == 0 || 2 * r == e))
				return false;
		}
		return true;
	}

	public static void main(String args[]) throws NumberFormatException, IOException {
		Scanner sc = new Scanner();
		N = sc.nextInt();
		array = new int[N];
		for(int i = 0; i < N; i++)
			array[i] = sc.nextInt() - 1;
		visited = new boolean[N];
		Arrays.fill(visited, false);
		TreeSet<Integer> tams = new TreeSet<Integer>();
		for(int i = 0; i < N; i++) {
			if (visited[i])
				continue;
			int ans = find(array[i], i, 1);
			if (ans == -1){
				System.out.println(-1);
				return;
			}
			if (ans > 1)
				tams.add(ans);
		}
		if (tams.size() == 0)
			System.out.println(1);
		else if (tams.size() == 1) {
			if (tams.first() % 2 == 0)
				System.out.println(tams.first() / 2);
			else
				System.out.println(tams.first());
		}
		else {
			int last = tams.pollLast();
			if (last % 2 == 0 && test(last/2, tams))
				System.out.println(last/2);
			else if (test(last, tams))
				System.out.println(last);
			else
				System.out.println(-1);
		}
	}

}