import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main {
	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;

		// InputStream inputStream = new FileInputStream("input.txt");
		// OutputStream outputStream = new FileOutputStream("output.txt");

		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);

		TaskA solver = new TaskA();

		solver.solve(in, out);

		out.close();
	}
}

class TaskA {

	public void solve(InputReader in, OutputWriter out) {

		int n = in.nextInt();
		int[] f = in.nextIntArray(n);

		int[] len = new int[n];
		int[] start = new int[n];
		int[] u = new int[n];
		for(int i=0; i<n; i++){
			Arrays.fill(u, 0);
			int cur = f[i], step=1;
			while(u[cur-1]==0){
				u[cur-1]=step++;
				cur = f[cur-1];
			}
			len[i] = step-u[cur-1];
			start[i] = u[cur-1];
		}

		/*
		for(int i=0; i<n; i++){
			System.out.print(len[i]+"("+start[i]+") ");
		}
		System.out.println();
		*/

		long a=1;
		for(int i=0; i<n; i++)
			if(start[i]==1) a = lcm(a,len[i]);
		long b = 0;
		for(int i=0; i<n; i++)
			b = Math.max(b,start[i]-1);

		//System.out.println(a+" "+b);
		out.write(a*(b/a+1));
	}

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

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

}

class InputReader {

	BufferedReader reader;
	StringTokenizer tokenizer;

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

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

		return tokenizer.nextToken();
	}

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

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

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

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

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

		return res;
	}

}

class OutputWriter {

	PrintWriter out;

	public OutputWriter(OutputStream stream) {
		out = new PrintWriter(
				new BufferedWriter(new OutputStreamWriter(stream)));
	}

	public void write(Object... o) {
		for (Object cur : o)
			out.print(cur);
	}

	public void writeln(Object... o) {
		write(o);
		out.println();
	}

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

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

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class C {
	static InputStreamReader isr = new InputStreamReader(System.in);
	static BufferedReader br = new BufferedReader(isr);

	static int[] readIntArray() throws IOException {
		String[] v = br.readLine().split(" ");
		int[] ans = new int[v.length];

		for (int i = 0; i < ans.length; i++) {
			ans[i] = Integer.valueOf(v[i]);
		}

		return ans;
	}

	static int[] vals;

	static int[] next(int[] c) {
		int[] ans = new int[c.length];
		for (int i = 0; i < ans.length; i++) {
			ans[i] = vals[c[i]];
		}

		return ans;
	}

	public static void main(String[] args) throws IOException {
		int[] l = readIntArray();
		vals = readIntArray();

		// Random r = new Random();
		// vals = new int[5];
		// for (int i = 0; i < vals.length; i++) {
		// vals[i] = r.nextInt(vals.length) + 1;
		// }

		for (int i = 0; i < vals.length; i++) {
			vals[i]--;
		}

		int[] nums = new int[vals.length];
		int[] adds = new int[vals.length];
		for (int i = 0; i < vals.length; i++) {
			int s1 = i;
			int s2 = s1;
			int s3 = s2;
			List<Integer> le = new ArrayList<Integer>();
			for (int j = 1; j < 5000; j++) {
				for (int j2 = 0; j2 < 1; j2++) {
					s2 = vals[s2];
				}
				for (int j2 = 0; j2 < 2; j2++) {
					s3 = vals[s3];
				}

				if (s2 == s3) {
					le.add(j);
					// if (i == 5)
					// System.out.println(i + " : " + j);
				}
			}

			nums[i] = le.get(0);
			adds[i] = le.get(1) - le.get(0);
		}

		long ans = nums[0];
		long step = adds[0];
		for (int i = 1; i < nums.length; i++) {
			while (true) {
				if (ans < nums[i] || ((ans - nums[i]) % adds[i]) != 0) {
					ans += step;
				} else {
					break;
				}
			}

			step = lcm(step, adds[i]);
		}

		// System.out.println(Arrays.toString(nums));
		// System.out.println(Arrays.toString(adds));
		System.out.println(ans);
	}

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

	static long gcd(long a, long b) {
		if (a < b)
			return gcd(b, a);

		while (b != 0) {
			long t = b;
			b = a % b;
			a = t;
		}

		return a;
	}
}

import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.io.InputStream;
import java.util.Random;
import java.util.Collection;
import java.math.BigInteger;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Queue;
import java.io.IOException;

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

class TaskC
{
    int n;
    ArrayList<Integer> G[], revG[];
    long ans;
    SCC scc;
    int sizeComp[];
    int next[];

    public void solve(int testNumber, FastReader in, PrintWriter out)
    {
        n = in.ni ();
        next = new int[n];
        G = new ArrayList[n];
        revG = new ArrayList[n];
        for (int i = 0; i < n; i++)
        {
            G[i] = new ArrayList<Integer> ();
            revG[i] = new ArrayList<Integer> ();
        }
        for (int i = 0; i < n; i++)
        {
            int x = in.ni () - 1;
            next[i] = x;
            G[i].add (x);
            revG[x].add (i);
        }
        scc = new SCC ();
        scc.getSCC (G, revG);
        ans = 0;
        sizeComp = new int[scc.numComp];
        int compressed[] = new int[scc.numComp];
        Arrays.fill (compressed, -1);
        for (int i = 0; i < n; i++)
        {
            int x = scc.comp[i];
            int y = scc.comp[next[i]];
            //edge from x to y in compressed graph
            if (x != y)
            {
                compressed[x] = y;
            }
            sizeComp[x]++;
        }
        ans = sizeComp[0];
        for (int i = 0; i < scc.numComp; i++)
        {
            ans = lcm (ans, sizeComp[i]);
        }
        //back bfs
        int minDist[] = new int[scc.numComp];
        int size[] = new int[scc.numComp];
        Arrays.fill (minDist, -1);
        Queue<Integer> queue = new ArrayDeque<Integer> ();
        for (int i = 0; i < scc.numComp; i++)
        {
            if (compressed[i] == -1)
            {
                minDist[i] = 0;
                size[i] = sizeComp[i];
                queue.add (i);
            }
        }
        long base = ans;
        while (!queue.isEmpty ())
        {
            int x = queue.poll ();

                while (minDist[x] > ans)
                {
                    ans += base;
                }
            for (int i = 0; i < scc.numComp; i++)
            {
                if (compressed[i] == x)
                {
                    queue.add (i);
                    minDist[i] = minDist[x] + 1;
                    size[i] = size[x];
                }
            }
        }
        out.println (ans);

//        int n = in.ni ();
//        int next[] = new int[n];
//        int cur[] = new int[n];
//        for (int i = 0; i < n; i++)
//        {
//            cur[i] = next[i] = in.ni () - 1;
//        }
//        int k = 1;
//        int temp[] = new int[n];
//        while (!idempotent (cur))
//        {
////            if (k == 8)
////            {
////                for (int i = 0; i < n; i++)
////                {
////                    out.println ((i + 1) + "->" + (cur[i] + 1));
////                }
////            }
//            k++;
//            for (int i = 0; i < n; i++)
//            {
//                temp[i] = next[cur[i]];
//            }
//            int t[] = temp;
//            temp = cur;
//            cur = t;
//        }
//        out.println (k);
    }

    private long lcm(long x, long y)
    {
        return (x / MathUtils.gcd (x, y)) * y;
    }

    //    private boolean idempotent(int[] cur)
//    {
//        for (int i = 0; i < cur.length; i++)
//        {
//            if (cur[cur[i]] != cur[i])
//            {
//                return false;
//            }
//        }
//        return true;
//    }

}

class SCC
{
    public int numComp; //number of SCC
    public int comp[];  //component number of vertex i from [0, numComp)
    int n;
    ArrayList<Integer> revG[];
    /*
    takes as input graph and its reverse
    Kosaraju two pass algorithm
    for explanation see techniques
    Also note that we have proceeded in topological order of actual Graph while calculation comp[]
     */
    public void getSCC(ArrayList<Integer> G[], ArrayList<Integer> revG[])
    {
        this.revG = revG;
        numComp = 0;
        n = G.length;
        comp = new int[n];
        Arrays.fill (comp, -1);
        int revPostOrder[] = new TopoSort ().topoSort (G); //actually not topo order, coz graph is cyclic
        for (int x : revPostOrder)
        {
            if (comp[x] == -1)
            {
                dfs (x);
                numComp++;
            }
        }
    }

    private void dfs(int i)
    {
        comp[i] = numComp;
        for (int v : revG[i])
        {
            if (comp[v] != -1)
            {
                continue;
            }
            dfs (v);
        }
    }
}

class FastReader
{

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

    public FastReader(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 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;
    }

    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);
    }
}

class MathUtils
{
    public static long gcd(long big, long small) // O(log min(a, b))
    {
        if (small == 0)
            return big;
        return gcd(small, big % small); // big%small<=small
    }

    // NCR DP
    // O(n*n) precomputation -> dp, no overflow

    /*factor sieve -> O(n/2) memory      */

    //    public static long fastMult( long a, long b, long m )
//    {
//        //from http://apps.topcoder.com/forums/?module=RevisionHistory&messageID=1221302
//        if(a>m)
//            a=a%m;
//        if(b>m)
//            b=b%m;
//        long ret = 0;
//        if(a<b)
//        {
//            long t = a;
//            a = b;
//            b = t;
//        }
//        while(b>0)
//        {
//            while(a<m)
//            {
//                if((b&1) != 0)
//                    ret += a;
//                a<<=1;
//                b>>=1;
//            }
//            a-=m;
//            while(ret>=m)
//                ret-=m;
//            if(a<b)
//            {
//                long t = a;
//                a = b;
//                b = t;
//            }
//        }
//        return ret;
//    }

}

class TopoSort
{
    boolean done[];
    int n;
    ArrayList<Integer> adjList[];
    public int topoOrder[];
    int revCtr;
    /*
    returns reversed post order of graph
    graph should be dag for order to be topologically sorted
     */
    public int[] topoSort(ArrayList<Integer> adjList[])
    {
        this.adjList = adjList;
        n = adjList.length;
        done = new boolean[n];
        topoOrder = new int[n];
        revCtr = n-1;
        for (int i = 0; i < n; i++)
        {
            if (!done[i])
            {
                done[i] = true;
                dfs (i);
            }
        }
        return topoOrder;
    }

    private void dfs(int i)
    {
        for (int v : adjList[i])
        {
            if(!done[v])
            {
                done[v] = true;
                dfs (v);
            }
        }
        topoOrder[revCtr--] = i;
    }
}

//import java.awt.Dimension;
import java.awt.Point;
import java.io.*;
import static java.lang.Math.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import java.util.*;
import static java.util.Arrays.*;
//import java.math.BigInteger;
//import static java.lang.Character.*;
//import static java.lang.Math.*;
//import static java.math.BigInteger.*;

//import static java.util.Arrays.*;

//import java.awt.Point; // interger !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//import java.awt.Polygon;
//import java.awt.Rectangle;
//import java.awt.geom.AffineTransform;
//import java.awt.geom.Line2D;
//import java.awt.geom.Point2D;
//import javafx.scene.shape.Line;
//import javafx.scene.transform.Rotate;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Main implements Runnable{

    // https://netbeans.org/kb/73/java/editor-codereference_ru.html#display

    static boolean oj;

    @Override
    public void run(){
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }
//
        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;

        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        //new Main().run();
        new Thread(null, new Main(), "myThread", 100 * 1024 * 1024).start();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
    //</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (Exception ex) {
                return null;
            }
        }
        return st.nextToken();
    }

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

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

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

    String nextLine() {
        try {
            return br.readLine();
        } catch (IOException ex) {
            return null;
        }
    }
}
//</editor-fold>

class Solver {

    void aser(boolean OK) {
        if (!OK) {
            Main.MLE();
        }
    }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

//    int n;
//    int[] f, fOrg;
//
//    void solve(){
//        n = sc.nextInt();
//        f = new int[n + 1];
//        for (int x = 1; x <= n; x++)
//            f[x] = sc.nextInt();
//        fOrg = f.clone();
//
//        for( int iter = 1; iter <= 14; ++iter ){
//            err.printf("iter: %5d", iter); err.print("    ");
//            for(int i = 1;i <= n; ++i) err.print(" " + f[i]);
//            if( cheack() ){
//                err.print("\t OK!");
//                //break;
//            }
//            err.println();
//
//            //
//            int[] fNext = new int[n + 1];
//            for (int x = 1; x <= n; x++) {
//                fNext[x] = fOrg[f[x]];
//            }
//            f = fNext;
//        }
//    }
//
//    private boolean cheack() {
//        for (int x = 1; x <= n; x++) {
//            if( f[f[x]] != f[x] ){
//                return false;
//            }
//        }
//        return true;
//    }

    int n;
    int[] f;

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

    long getCyc(final int start){
        int[] timeIn = new int[n + 1];
        fill( timeIn, -1 );
        for( int v = start, timer = 0; ; v = f[v], ++timer ){
            if (timeIn[v] != -1) {
                if( start == v )
                    return timer;
                else
                    return -timeIn[v];
            }
            timeIn[v] = timer;
        }
    }

    void solve(){
        n = sc.nextInt();
        f = new int[n + 1];
        for (int x = 1; x <= n; x++)
            f[x] = sc.nextInt();
        long maxDist = 0;
        long lcm = 0;
        for (int start = 1; start <= n; start++) {
            long c = getCyc(start);
            if( c < 0 ) maxDist = max( maxDist, -c );
            else {
                if( lcm == 0 ) lcm = c;
                else lcm = lcm / gcd(lcm,c) * c;
            }
            err.printf("%d %d\n", start, c);
        }
        if( lcm < maxDist )
            lcm *= (maxDist + lcm - 1) / lcm;
        out.println(lcm);
    }

}

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Main {

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

		InputReader sc = new InputReader(new BufferedInputStream(System.in));
		PrintWriter out = new PrintWriter(new BufferedWriter(
				new OutputStreamWriter(System.out)));

		int size = sc.nextInt();
		ArrayList<Integer> stringGraph = new ArrayList<Integer>();
		for (int i = 0; i < size; i++) {
			stringGraph.add(sc.nextInt());
		}
		Graph g = new Graph(size, stringGraph);
		out.print(g.findIdempotent());

		out.flush();
		out.close();

	}

	public static long gcd(long a, long b) //valid for positive integers.
	{
		while(b > 0)
		{
			long c = a % b;
			a = b;
			b = c;
		}
		return a;
	}

	public static long lcm(long m, long n) {
		return (m*n)/gcd(m,n);
	}

}

class InputReader {
	BufferedReader reader;
	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 long nextLong() {
		return Long.parseLong(next());
	}

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

class GraphNode {

	private boolean visited;
	private int content;
	private ArrayList<Edge> edges;

	public int getContent() {
		return content;
	}

	public ArrayList<Edge> getInComes() {
		return (ArrayList<Edge>) edges.subList(1, edges.size() - 1);
	}

	public void addEdgeToInComes(Edge add) {
		this.edges.add(add);
	}

	public Edge getOutGoing() {
		return edges.get(0);
	}

	public void addOutGoingEdge(Edge add) {
		this.edges.add(0, add);
	}

	public GraphNode(int content) {
		this.content = content;
		this.edges = new ArrayList<Edge>();
		this.visited = false;
	}

	public int getInDegree() {
		return edges.subList(1, edges.size()).size();
	}

	public boolean isVisited() {
		return visited;
	}

	public void setVisited(boolean visited) {
		this.visited = visited;
	}

	public ArrayList<Edge> getEdges() {
		return this.edges;
	}
}

class Graph {
	private ArrayList<GraphNode> nodes;

	public Graph(int size, ArrayList<Integer> edges) {
		nodes = new ArrayList<GraphNode>();
		for (int i = 1; i <= size; i++) {
			nodes.add(new GraphNode(i));
		}
		for (int i = 0; i < edges.size(); i++) {
			addEdge(i + 1, edges.get(i));
		}
	}

	public void addEdge(int from, int to) {
		new Edge(nodes.get(from - 1), nodes.get(to - 1));
	}

	public int depthFirstSearch(BinaryTree<Integer> visitTree,
			ArrayList<GraphNode> startNodes, BinaryTree<Integer> cycleNodes,
			GraphNode current) {
		int k = -1;
		current.setVisited(true);
		visitTree.delete(current.getContent());

		if (current.getInDegree() == 0) {
			startNodes.add(current);
		}

		for (int i = 0; i < current.getEdges().size(); i++) {
			if (!current.getEdges().get(i).isVisited()) {
				GraphNode adjacent;
				if (i == 0)
					adjacent = current.getEdges().get(i).getTo();
				else
					adjacent = current.getEdges().get(i).getFrom();
				current.getEdges().get(i).setVisited(true);
				if (!adjacent.isVisited()) {
					int m = depthFirstSearch(visitTree, startNodes, cycleNodes,
							adjacent);
					if (m > 0) {
						k = m;
					}
				} else {
					k = adjacent.getContent();
				}
			}
		}

		if (k != -1) {
			cycleNodes.add(current.getContent());
		}
		if (k == current.getContent()) {
			k = -1;
		}
		return k;
	}

	public long findIdempotent() {
		ArrayList<Integer> visit = new ArrayList<Integer>();
		for (int i = 1; i <= this.nodes.size(); i++) {
			visit.add(i);
		}
		int distanceToCycle = 1;
		ArrayList<Integer> sizeOfCyles = new ArrayList<Integer>();
		BinaryTree<Integer> visitTree = new BinaryTree<Integer>(
				Integer.MAX_VALUE, visit);
		while (visitTree.size() > 0) {
			BinaryTree<Integer> cycleNodes = new BinaryTree<Integer>(
					Integer.MAX_VALUE);
			ArrayList<GraphNode> startNodes = new ArrayList<GraphNode>();
			depthFirstSearch(visitTree, startNodes, cycleNodes,
					this.nodes.get(visitTree.peek() - 1));
			sizeOfCyles.add(cycleNodes.size());
			while (!startNodes.isEmpty()) {
				int distance = 1;
				GraphNode mover = startNodes.remove(startNodes.size() - 1);
				while (true) {
					if (cycleNodes.contains(mover.getOutGoing().getTo()
							.getContent())) {
						break;
					}
					distance++;
					mover = mover.getOutGoing().getTo();
				}
				if (distance > distanceToCycle) {
					distanceToCycle = distance;
				}
			}
		}
		long lcm = sizeOfCyles.remove(sizeOfCyles.size() - 1);
		while (sizeOfCyles.size() > 0) {
			lcm = Main.lcm(lcm, sizeOfCyles.remove(sizeOfCyles.size() - 1));
		}
		return (long) (Math.ceil((double) distanceToCycle / lcm)) * lcm;
	}
}

class BinaryTree<T extends Comparable<T>> {
	private Node<T> header;
	private int numberOfElements;

	public BinaryTree(T header) {
		this.header = new Node<T>(header);
		numberOfElements = 0;
	}

	public BinaryTree(T header, ArrayList<T> list) {
		this(header);
		this.header.setLeftChild(sortedListToTree(0, list.size() - 1, list));
	}

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

	public Node<T> getHeader() {
		return this.header;
	}

	public void print(Node<T> a) {
		if (a != null) {
			print(a.getLeftChild());
			System.out.println(a.getContent());
			print(a.getRightChild());
		}
	}

	private Node<T> sortedListToTree(int left, int right, ArrayList<T> list) {
		Node<T> ret = null;
		if (left <= right) {
			int middle = (left + right) / 2;
			ret = new Node<T>(list.get(middle));
			ret.setLeftChild(sortedListToTree(left, middle - 1, list));
			ret.setRightChild(sortedListToTree(middle + 1, right, list));
		}
		this.numberOfElements = list.size();
		return ret;
	}

	public void add(T add) {
		Node<T> rear = null;
		Node<T> front = this.header;
		boolean leftOrRight = true;
		while (front != null) {
			if (add.compareTo(front.getContent()) > 0) {
				rear = front;
				front = front.getRightChild();
				leftOrRight = false;
			} else if (add.compareTo(front.getContent()) < 0) {
				rear = front;
				front = front.getLeftChild();
				leftOrRight = true;
			} else {
				break;
			}
		}
		if (leftOrRight) {
			rear.setLeftChild(new Node<T>(add));
		} else {
			rear.setRightChild(new Node<T>(add));
		}
		this.numberOfElements++;
	}

	public boolean contains(T search) {
		if (find(search) != null) {
			return true;
		} else {
			return false;
		}
	}

	public Node<T> find(T key) {
		Node<T> found = null, mover = this.header;
		while (mover != null) {
			if (key.compareTo(mover.getContent()) > 0) {
				mover = mover.getRightChild();
			} else if (key.compareTo(mover.getContent()) < 0) {
				mover = mover.getLeftChild();
			} else {
				found = mover;
				break;
			}
		}
		return found;
	}

	public void delete(T deleteNum) {
		Node<T> mover = this.header;
		Node<T> backMover = null;
		while (mover != null) {
			if (deleteNum.equals(mover.getContent())) {
				break;
			} else if (deleteNum.compareTo(mover.getContent()) == -1) {
				backMover = mover;
				mover = mover.getLeftChild();
			} else {
				backMover = mover;
				mover = mover.getRightChild();
			}
		}

		Node<T> replace = null;
		Node<T> backReplace = null;

		if (mover.getLeftChild() != null) {
			replace = mover.getLeftChild();
			while (replace.getRightChild() != null) {
				backReplace = replace;
				replace = replace.getRightChild();
			}
			if (backReplace != null) {
				backReplace.setRightChild(replace.getLeftChild());
				replace.setLeftChild(mover.getLeftChild());
			}
			replace.setRightChild(mover.getRightChild());
		} else if (mover.getRightChild() != null) {
			replace = mover.getRightChild();
			while (replace.getLeftChild() != null) {
				backReplace = replace;
				replace = replace.getLeftChild();
			}
			if (backReplace != null) {
				backReplace.setLeftChild(replace.getRightChild());
				replace.setRightChild(mover.getRightChild());
			}
			replace.setLeftChild(mover.getLeftChild());
		}

		if (mover.getContent().compareTo(backMover.getContent()) == -1) {
			backMover.setLeftChild(replace);
		} else {
			backMover.setRightChild(replace);
		}
		this.numberOfElements--;
	}

	public T pop() {
		T temp = this.header.getLeftChild().getContent();
		delete(temp);
		return temp;
	}

	public T peek() {
		return this.header.getLeftChild().getContent();
	}
}

class Edge {
	private GraphNode from;
	private GraphNode to;
	private boolean visited;

	public Edge(GraphNode from, GraphNode to) {
		this.from = from;
		this.to = to;
		this.visited = false;
		from.addOutGoingEdge(this);
		to.addEdgeToInComes(this);
	}

	public GraphNode getFrom() {
		return from;
	}

	public void setFrom(GraphNode from) {
		this.from = from;
	}

	public GraphNode getTo() {
		return to;
	}

	public void setTo(GraphNode to) {
		this.to = to;
	}

	public boolean isVisited() {
		return visited;
	}

	public void setVisited(boolean visited) {
		this.visited = visited;
	}

}

class Node<T> {
	private T content;
	private Node<T> rightChild;
	private Node<T> leftChild;

	public Node<T> getRightChild() {
		return rightChild;
	}

	public void setRightChild(Node<T> rightChild) {
		this.rightChild = rightChild;
	}

	public Node<T> getLeftChild() {
		return leftChild;
	}

	public void setLeftChild(Node<T> leftChild) {
		this.leftChild = leftChild;
	}

	public Node(T content) {
		super();
		this.content = content;
	}

	public T getContent() {
		return content;
	}

	public void setContent(T content) {
		this.content = content;
	}

}

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

public class C {

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

    void solve() throws IOException {
        in = new InputReader("__std");
        out = new OutputWriter("__std");

        int n = in.readInt();
        int[] f = new int[n];
        for (int i = 0; i < n; ++i) {
            f[i] = in.readInt() - 1;
        }
        int len = 0;
        long lcm = 1;
        for (int i = 0; i < n; ++i) {
            int[] c = new int[n];
            int t = 1;
            c[i] = t++;
            int j = f[i];
            while (c[j] == 0) {
                c[j] = t++;
                j = f[j];
            }
            len = Math.max(len, c[j] - 1);
            lcm = lcm * (t - c[j]) / gcd(lcm, t - c[j]);
        }
        long k = lcm;
        while (k < len) k += lcm;
        out.println(k);

        exit();
    }

    void exit() {
        //System.err.println((System.currentTimeMillis() - startTime) + " ms");
        out.close();
        System.exit(0);
    }

    InputReader in;
    OutputWriter out;

    //long startTime = System.currentTimeMillis();

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

    class InputReader {

        private InputStream stream;

        private byte[] buffer = new byte[1024];
        private int pos, len;

        private int cur;

        private StringBuilder sb = new StringBuilder(32);

        InputReader(String name) throws IOException {
            if (name.equals("__std")) {
                stream = System.in;
            } else {
                stream = new FileInputStream(name);
            }
            cur = read();
        }

        private int read() throws IOException {
            if (len == -1) {
                throw new EOFException();
            }
            if (pos >= len) {
                pos = 0;
                len = stream.read(buffer);
                if (len == -1) return -1;
            }
            return buffer[pos++];
        }

        private boolean whitespace() {
            return cur == ' ' || cur == '\t' || cur == '\r' || cur == '\n' || cur == -1;
        }

        char readChar() throws IOException {
            if (cur == -1) {
                throw new EOFException();
            }
            char res = (char) cur;
            cur = read();
            return res;
        }

        int readInt() throws IOException {
            if (cur == -1) {
                throw new EOFException();
            }
            while (whitespace()) {
                cur = read();
            }
            if (cur == -1) {
                throw new EOFException();
            }
            int sign = 1;
            if (cur == '-') {
                sign = -1;
                cur = read();
            }
            int res = 0;
            while (!whitespace()) {
                if (cur < '0' || cur > '9') {
                    throw new NumberFormatException();
                }
                res *= 10;
                res += cur - '0';
                cur = read();
            }
            return res * sign;
        }

        long readLong() throws IOException {
            if (cur == -1) {
                throw new EOFException();
            }
            return Long.parseLong(readToken());
        }

        double readDouble() throws IOException {
            if (cur == -1) {
                throw new EOFException();
            }
            return Double.parseDouble(readToken());
        }

        String readLine() throws IOException {
            if (cur == -1) {
                throw new EOFException();
            }
            sb.setLength(0);
            while (cur != -1 && cur != '\r' && cur != '\n') {
                sb.append((char) cur);
                cur = read();
            }
            if (cur == '\r') {
                cur = read();
            }
            if (cur == '\n') {
                cur = read();
            }
            return sb.toString();
        }

        String readToken() throws IOException {
            if (cur == -1) {
                throw new EOFException();
            }
            while (whitespace()) {
                cur = read();
            }
            if (cur == -1) {
                throw new EOFException();
            }
            sb.setLength(0);
            while (!whitespace()) {
                sb.append((char) cur);
                cur = read();
            }
            return sb.toString();
        }

        boolean eof() {
            return cur == -1;
        }
    }

    class OutputWriter {

        private PrintWriter writer;

        OutputWriter(String name) throws IOException {
            if (name.equals("__std")) {
                writer = new PrintWriter(System.out);
            } else {
                writer = new PrintWriter(name);
            }
        }

        void print(String format, Object ... args) {
            writer.print(new Formatter(Locale.US).format(format, args));
        }

        void println(String format, Object ... args) {
            writer.println(new Formatter(Locale.US).format(format, args));
        }

        void print(Object value) {
            writer.print(value);
        }

        void println(Object value) {
            writer.println(value);
        }

        void println() {
            writer.println();
        }

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

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

/**
 * 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);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int count = in.readInt();
        int[] f = IOUtils.readIntArray(in, count);
        MiscUtils.decreaseByOne(f);
        boolean[] present = ArrayUtils.createArray(count, true);
        boolean[] next = new boolean[count];
        int min = 0;
        while (true) {
            Arrays.fill(next, false);
            for (int i = 0; i < count; i++) {
                if (present[i]) {
                    next[f[i]] = true;
                }
            }
            boolean same = true;
            for (int i = 0; i < count; i++) {
                if (present[i] != next[i]) {
                    same = false;
                    break;
                }
            }
            if (same) {
                break;
            }
            boolean[] temp = present;
            present = next;
            next = temp;
            min++;
        }
        BigInteger answer = BigInteger.ONE;
        for (int i = 0; i < count; i++) {
            if (!present[i]) {
                continue;
            }
            int length = 0;
            int j = i;
            do {
                j = f[j];
                length++;
            } while (j != i);
            BigInteger current = BigInteger.valueOf(length);
            answer = answer.multiply(current).divide(answer.gcd(current));
        }
        BigInteger atLeast = BigInteger.valueOf(min);
        BigInteger baseAnswer = answer;
        while (answer.compareTo(atLeast) < 0) {
            answer = answer.add(baseAnswer);
        }
        out.printLine(answer);
    }
}

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);
	}
}

class OutputWriter {
	private final PrintWriter writer;

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

	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();
	}

}

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;
	}

}

class MiscUtils {

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

}

class ArrayUtils {

	public static boolean[] createArray(int count, boolean value) {
		boolean[] array = new boolean[count];
		Arrays.fill(array, value);
		return array;
	}

}

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

public class C
{
	int[] f;
	int N;

	void solve()
	{
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		f = new int[N];
		for (int i = 0; i < N; i++)
			f[i] = sc.nextInt() - 1;
		TreeSet<Integer> constraints = new TreeSet<Integer>();
		int minVal = 0;
		for (int i = 0; i < N; i++)
		{
			int[] dist = new int[N];
			Arrays.fill(dist, -1);
			int cnt = 0;
			int v = i;
			while (true)
			{
				if (dist[v] >= 0)
				{
					minVal = Math.max(minVal, dist[v]);
					constraints.add(cnt - dist[v]);
					break;
				}
				dist[v] = cnt++;
				v = f[v];
			}
		}
		BigInteger lo = BigInteger.valueOf(minVal);
		BigInteger ans = BigInteger.ONE;
		for (int x : constraints)
		{
			BigInteger o = BigInteger.valueOf(x);
			ans = ans.multiply(o).divide(ans.gcd(o));
		}
		BigInteger fans = ans;
		while (fans.compareTo(lo) < 0)
			fans = fans.add(ans);
		System.out.println(fans);
	}

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

import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.math.BigInteger;
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);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskC {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n=in.readInt(), max=0;
        int[] f= IOUtils.readIntArray(in, n);
        MiscUtils.decreaseByOne(f);
        long lcm=1;
        for (int i=0; i<n; i++) {
            IntPair pair=run(f, i);
            max=Math.max(max, pair.first);
            lcm= IntegerUtils.lcm(lcm, pair.second);
        }
        int i;
        for (i=1; lcm*i<max; i++);
        lcm*=i;
        out.printLine(lcm);
    }

    IntPair run(int[] f, int idx) {
        int[] arr=new int[f.length+1];
        Arrays.fill(arr, -1);
        for (int i=0; ; i++, idx=f[idx]) {
            if (arr[idx]==-1) arr[idx]=i;
            else return new IntPair(arr[idx], i-arr[idx]);
        }
    }
}

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);
    }
}

class OutputWriter {
    private final PrintWriter writer;

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

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

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

}

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;
    }

}

class MiscUtils {

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

}

class IntPair implements Comparable<IntPair> {
    public final int first, second;

    public IntPair(int first, int second) {
        this.first = first;
        this.second = second;
    }

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

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        IntPair intPair = (IntPair) o;

        return first == intPair.first && second == intPair.second;

    }

    public int hashCode() {
        int result = first;
        result = 31 * result + second;
        return result;
    }

    public int compareTo(IntPair o) {
        if (first < o.first)
            return -1;
        if (first > o.first)
            return 1;
        if (second < o.second)
            return -1;
        if (second > o.second)
            return 1;
        return 0;
    }
}

class IntegerUtils {
    public static long gcd(long a, long b) {
        a = Math.abs(a);
        b = Math.abs(b);
        while (b != 0) {
            long temp = a % b;
            a = b;
            b = temp;
        }
        return a;
    }

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

}

import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.Set;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.TreeSet;
import java.io.Writer;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Andrey Rechitsky (arechitsky@gmail.com)
 */
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);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
    public void solve(int testNumber, FastScanner in, FastPrinter out) {
        int n = in.nextInt();
        int []f = new int[n];
        for (int i = 0; i < n; i++) {
            f[i] = in.nextInt()-1;
        }
        int[]prefix = new int[n];
        int[]cycle = new int[n];
        for (int i = 0; i < n; i++) {
            int tmp = i;
            for (int j = 0; j < n; j++) {
                tmp = f[tmp];
            }
            int tmp2 = f[tmp];
            cycle[i] = 1;
            while (tmp2 != tmp){
                tmp2 = f[tmp2];
                cycle[i]++;
            }
            tmp = i;
            tmp2 = i;
            for (int j = 0; j < cycle[i]; j++) {
                tmp2 = f[tmp2];
            }
            prefix[i] = 0;
            while (tmp2 != tmp){
                tmp2 = f[tmp2];
                tmp = f[tmp];
                prefix[i]++;
            }
        }
        long ans = 1;
        for (int i = 0; i < n; i++) {
            ans = NumberUtils.LCM(ans, cycle[i]);
        }
        long ans2 = ans;
        int mp = 0;
        for (int i = 0; i < n; i++) {
            mp = Math.max(mp, prefix[i]);
        }
        while (ans2<mp) ans2+=ans;
        out.printLine(ans2);
    }
}

class FastScanner {

    private BufferedReader reader;
    private StringTokenizer st;

    public FastScanner(InputStream stream) {
        this.reader = new BufferedReader(new InputStreamReader(stream));
        this.st = new StringTokenizer("");
    }

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

    public String next(){
        while (!st.hasMoreTokens()){
            st = new StringTokenizer(readLine());
        }
        return st.nextToken();
    }

    private String readLine() {
        try {
            String line = reader.readLine();
            if (line==null) throw new InputMismatchException();
            return line;
        } catch (IOException e) {
            throw new InputMismatchException();
        }
    }

}

class FastPrinter {
    private final PrintWriter writer;

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

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

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

}

class NumberUtils {

    public static long GCD(long a, long b) {
        a = Math.abs(a);
        b = Math.abs(b);
        if (a < b) return GCD(b, a);
        while (b > 0) {
            long c = a % b;
            a = b;
            b = c;
        }
        return a;
    }

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

}

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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Vadim Semenov
 */
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();
	}
}

class TaskC {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int counter = in.nextInt();
        int[] f = new int[counter];
        for (int i = 0; i < counter; ++i) {
            f[i] = in.nextInt() - 1;
        }
        long lcm = 1;
        int globalOffset = 0;
        for (int i = 0; i < counter; ++i) {
            int[] time = new int[counter];
            int current = i;
            int currentTime = 1;
            while (time[current] == 0) {
                time[current] = currentTime++;
                current = f[current];
            }
            int cycleLength = currentTime - time[current];
            int offset = time[current] - 1;
            globalOffset = Math.max(globalOffset, offset);
            long gcd = gcd(lcm, cycleLength);
            lcm /= gcd;
            lcm *= cycleLength;
        }
        long answer = lcm;
        while (answer < globalOffset) {
            answer += lcm;
        }
        out.println(answer);
    }

    private long gcd(long first, long second) {
        while (second != 0) {
            long tmp = first % second;
            first = second;
            second = tmp;
        }
        return first;
    }
}

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;
    }
}

//package codeforce;
import java.io.*;
import java.util.*;
public class idempotentcomponents {
public static void main(String[] args) throws Exception
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw=new PrintWriter(System.out);
    int n=Integer.parseInt(br.readLine());
    StringTokenizer st=new StringTokenizer(br.readLine());
    int[] a=new int[n];
    for(int i=0;i<n;i++)
    {

    a[i]=Integer.parseInt(st.nextToken())-1;

    }
    long min=1;
    long z=1;
    for(int i=0;i<n;i++)
    {

        HashMap<Integer,Integer> hs=new HashMap();
        hs.put(i,0);
        int next=a[i];

        int k=1;
        while(!hs.containsKey(next))
        {
            hs.put(next, k);
            k++;
            next=a[next];
        }
        //System.out.println(next+" "+k);
        if(next==i)
        {
            z=lcm(z,k);
        }
        else
        {
            if((k=hs.get(next))>min)
            {
                min=k;
            }
        }
        //System.out.println("min is"+min+" z is   "+z);

    }
    //System.out.println(min%z == 0? min:(min/z+1)*z);
if(min%z==0)
    {
        System.out.println(min);
    }
    else
    {
        System.out.println((min/z+1)*z);
    }
    }

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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * #
 * @author pttrung
 */
public class C_VK2015_Round_3 {

    public static int[][] dp;
    public static long MOD = 1000000007;

    public static void main(String[] args) throws FileNotFoundException {
        // PrintWriter out = new PrintWriter(new FileOutputStream(new File(
        // "output.txt")));
        PrintWriter out = new PrintWriter(System.out);
        Scanner in = new Scanner();
        int n = in.nextInt();
        dp = new int[n + 1][n + 1];
        for (int[] a : dp) {
            Arrays.fill(a, -1);
        }
        int[] data = new int[n + 1];
        for (int i = 0; i < n; i++) {
            data[i + 1] = in.nextInt();
        }
        int max = 0;
        boolean ok = true;
        HashSet<Point> set = new HashSet();
        for (int i = 1; i <= n; i++) {
            int cycle = cal(i, 1, data, new int[n + 1]);

            int v = 0;
            for (int j = 1; j <= n; j++) {
                int a = f(i, j, data);
                int b = f(a, j, data);
                if (a == b) {
                    v = j;
                    break;
                }
            }
            max = Math.max(v, max);
            v %= cycle;
            if (v != 0) {
                ok = false;
            }
            set.add(new Point(cycle, v));
        }
        if (ok) {
            long re = 1;
            for(Point p : set){
                re = re*p.x/gcd(re, p.x);
            }
            long start = re;
            while(re < max){
                re += start;
            }
            out.println(re);
        } else {
            //System.out.println(max + " " + set);
            out.println(CRT(set, max));
        }
        out.close();
    }

    public static long CRT(HashSet<Point> set, long min) {
        long M = 1;
        long[] m = new long[set.size()];
        long[] x = new long[set.size()];
        int index = 0;
        for (Point p : set) {
            M *= p.x;
            m[index] = p.x;
            x[index] = p.y;
            index++;
        }
        long[] a = new long[set.size()];
        long[] b = new long[set.size()];
        long result = 0;
        for (int i = 0; i < index; i++) {
            a[i] = M / m[i];
            b[i] = modularLinearSolver(a[i], 1, m[i]);
            result += x[i] * a[i] * b[i];
        }
        while (result < min) {
            result += M;
        }
        return result;

    }

    static long[] extendEuclid(long a, long b) {
        if (b == 0) {
            return new long[]{a, 1, 0};
        }
        long[] re = extendEuclid(b, a % b);
        long x = re[2];
        long y = re[1] - (a / b) * re[2];
        re[1] = x;
        re[2] = y;
        return re;

    }

    static long modularLinearSolver(long a, long b, long n) {
        long[] ex = extendEuclid(a, n);
        if (b % ex[0] != 0) {
            throw new IllegalArgumentException("No solution");
        }
        long result = (ex[1] * (b / ex[0])) % n;

        return result;
    }

    public static int cal(int index, int step, int[] data, int[] last) {
        if (last[index] != 0) {
            return step - last[index];
        }
        last[index] = step;
        return cal(data[index], step + 1, data, last);
    }

    public static int f(int index, int left, int[] data) {
        if (left == 0) {
            return index;
        }
        return f(data[index], left - 1, data);
    }

    public static int[] KMP(String val) {
        int i = 0;
        int j = -1;
        int[] result = new int[val.length() + 1];
        result[0] = -1;
        while (i < val.length()) {
            while (j >= 0 && val.charAt(j) != val.charAt(i)) {
                j = result[j];
            }
            j++;
            i++;
            result[i] = j;
        }
        return result;

    }

    public static boolean nextPer(int[] data) {
        int i = data.length - 1;
        while (i > 0 && data[i] < data[i - 1]) {
            i--;
        }
        if (i == 0) {
            return false;
        }
        int j = data.length - 1;
        while (data[j] < data[i - 1]) {
            j--;
        }
        int temp = data[i - 1];
        data[i - 1] = data[j];
        data[j] = temp;
        Arrays.sort(data, i, data.length);
        return true;
    }

    public static int digit(long n) {
        int result = 0;
        while (n > 0) {
            n /= 10;
            result++;
        }
        return result;
    }

    public static double dist(long a, long b, long x, long y) {
        double val = (b - a) * (b - a) + (x - y) * (x - y);
        val = Math.sqrt(val);
        double other = x * x + a * a;
        other = Math.sqrt(other);
        return val + other;

    }

    public static class Point implements Comparable<Point> {

        int x, y;

        public Point(int start, int end) {
            this.x = start;
            this.y = end;
        }

        @Override
        public int hashCode() {
            int hash = 5;
            hash = 47 * hash + this.x;
            hash = 47 * hash + this.y;
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Point other = (Point) obj;
            if (this.x != other.x) {
                return false;
            }
            if (this.y != other.y) {
                return false;
            }
            return true;
        }

        @Override
        public int compareTo(Point o) {
            return x - o.x;
        }
    }

    public static class FT {

        long[] data;

        FT(int n) {
            data = new long[n];
        }

        public void update(int index, long value) {
            while (index < data.length) {
                data[index] += value;
                index += (index & (-index));
            }
        }

        public long get(int index) {
            long result = 0;
            while (index > 0) {
                result += data[index];
                index -= (index & (-index));
            }
            return result;

        }
    }

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

    public static long pow(long a, long b, long MOD) {
        if (b == 0) {
            return 1;
        }
        if (b == 1) {
            return a;
        }
        long val = pow(a, b / 2, MOD);
        if (b % 2 == 0) {
            return val * val % MOD;
        } else {
            return val * (val * a % MOD) % MOD;

        }
    }

    static class Scanner {

        BufferedReader br;
        StringTokenizer st;

        public Scanner() throws FileNotFoundException {
            // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
            br = new BufferedReader(new InputStreamReader(System.in));
            //  br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
        }

        public String next() {

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

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

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

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

        public String nextLine() {
            st = null;
            try {
                return br.readLine();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }

        public boolean endLine() {
            try {
                String next = br.readLine();
                while (next != null && next.trim().isEmpty()) {
                    next = br.readLine();
                }
                if (next == null) {
                    return true;
                }
                st = new StringTokenizer(next);
                return st.hasMoreTokens();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
}

import java.io.*;
import java.text.NumberFormat;
import java.util.*;

/**
 * Created by VIET ANH on 27/04/2015.
 */
public class test {

    private static int T;
    private static long oo=Long.MAX_VALUE;

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n=in.nextInt();
        int[] f=new int [300];
        int[] dau=new int[300];
        boolean[] incir=new boolean[300];
        long vlcm=1;
        for (int i = 1; i <= n; i++) f[i] = in.nextInt();
        int dem=0;
        for (int i = 1; i <= n; i++) {
            int x=i;
            int cir=0;
            dem++;
            while (dau[x] == 0) {
                dau[x] = dem;
                x=f[x];
            }
            if (dau[x]!=dem) continue;
            int y=x;
            do{
                cir++;
                incir[y]=true;
                y=f[y];
            } while (y!=x);
            if (cir!=0) vlcm=lcm(vlcm,cir);
        }
        int maxpath=0;
        for (int i = 1; i <= n; i++) {
            int x=i;
            int path=0;
            while (!incir[x]) {
                path++;
                x = f[x];
            }
            maxpath=Math.max(maxpath,path);
        }
        if (vlcm<maxpath)
            if (maxpath%vlcm==0) vlcm=maxpath;
            else vlcm=(maxpath/vlcm+1)*vlcm;
        out.print(vlcm);
        out.close();
    }

    private static long lcm(long vlcm, long cir) {
        return vlcm*cir/gcd(vlcm,cir);
    }

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

}

import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
import java.util.InputMismatchException;
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();
	}
}

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

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

    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.readInt();
        int[] f = new int[n];
        for (int i = 0; i < n; ++i) {
            f[i] = in.readInt() - 1;
        }

        boolean[] present = new boolean[n];
        Arrays.fill(present, true);
        int minRes = 0;
        while (true) {
            boolean[] next = new boolean[n];
            for (int i = 0; i < n; ++i) {
                if (present[i]) {
                    next[f[i]] = true;
                }
            }
            boolean same = true;
            for (int i = 0; i < n; ++i) {
                if (next[i] != present[i]) {
                    same = false;
                    break;
                }
            }
            if (same) {
                break;
            }
            minRes++;
            System.arraycopy(next, 0, present, 0, n);
        }
        long res = 1;
        for (int i = 0; i < n; ++i) {
            if (present[i]) {
                int len = 0;
                int j = i;
                do {
                    j = f[j];
                    len++;
                } while (j != i);

                res = lcm(res, len);
            }
        }
        long a = res;
        while (res < minRes) {
            res += a;
        }
        out.println(res);
    }

}

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 UnknownError();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new UnknownError();
            }
            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();
        } else if (c == '+') {
            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 static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

}

/* 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 Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int f[] = new int[n];
        for(int i = 0;i<n;i++){
            f[i]=sc.nextInt()-1;
        }
        int a[] = new int[n];
        long answer=1;
        long min = 1;
        for(int i = 0;i<n;i++){
            int b[] = new int[n];
            for(int j = 0;j<n;j++){
                b[j]=-1;
            }
            int x = 0;
            int y = i;
            int first = -1;
            int second = -1;
            while(true){
                if(b[y]==-1){
                    b[y]=x;
                }
                else{
                    first = b[y];
                    second = x;
                    break;
                }
                y=f[y];
                x++;
            }
            long p =(long)(second-first);
            min=Math.max(min,first);
            answer=(p*answer)/GCD(answer,p);
        }
        System.out.println((((long)min+answer-1)/answer)*answer);
    }
    public static long GCD(long a, long b) { return b==0 ? a : GCD(b, a%b); }
}

import java.math.*;

public class C {

	public C () {
		int N = sc.nextInt();
		int [] F = dec(sc.nextInts());

		int [] R = new int [N];
		int [] T = new int [N];

		for (int i : rep(N)) {
			int c = 1, x = F[i];
			for (int j : rep(N + 10)) {
				if (x == i) {
					R[i] = c;
					break;
				}
				x = F[x]; ++c;
			}
		}

		for (int i : rep(N)) {
			if (R[i] > 0)
				continue;
			int c = 1, x = F[i];
			for (int j : rep(N + 10)) {
				if (R[x] > 0) {
					T[i] = c;
					break;
				}
				x = F[x]; ++c;
			}
		}

		long L = 1;
		for (int i : rep(N))
			if (R[i] > 0)
				L = lcm(L, R[i]);

		long res = L;
		for (int i : rep(N))
			while (res < T[i])
				res += L;

		exit(res);
	}

	private static int [] dec(int ... A) {
		int [] res = A.clone();
		for (int i = 0; i < A.length; ++i)
			--res[i];
		return res;
	}
	private static long gcd(long x, long y) { return BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).longValue(); }
	private static long lcm(long x, long y) { return x/gcd(x, y)*y; }
	private static int [] rep(int N) { return rep(0, N); }
	private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
	////////////////////////////////////////////////////////////////////////////////////
	private final static IOUtils.MyScanner sc = new IOUtils.MyScanner();
	private static void exit (Object o, Object ... A) { IOUtils.print(o, A); IOUtils.exit(); }
	private static class IOUtils {
		public static class MyScanner {
			public String next() { newLine(); return line[index++]; }
			public int nextInt() { return Integer.parseInt(next()); }
			public String nextLine() { line = null; return readLine(); }
			public String [] nextStrings() { return split(nextLine()); }
			public int [] nextInts() {
				String [] L = nextStrings();
				int [] res = new int [L.length];
				for (int i = 0; i < L.length; ++i)
					res[i] = Integer.parseInt(L[i]);
				return res;
			}
			//////////////////////////////////////////////
			private boolean eol() { return index == line.length; }
			private String readLine() {
				try {
					return r.readLine();
				} catch (Exception e) {
					throw new Error (e);
				}
			}
			private final java.io.BufferedReader r;
			private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
			private MyScanner (java.io.BufferedReader r) {
				try {
					this.r = r;
					while (!r.ready())
						Thread.sleep(1);
					start();
				} catch (Exception e) {
					throw new Error(e);
				}
			}
			private String [] line;
			private int index;
			private void newLine() {
				if (line == null || eol()) {
					line = split(readLine());
					index = 0;
				}
			}
			private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
		}
		private static String build(Object o, Object ... A) { return buildDelim(" ", o, A); }
		private static String buildDelim(String delim, Object o, Object ... A) {
			StringBuilder b = new StringBuilder();
			append(b, o, delim);
			for (Object p : A)
				append(b, p, delim);
			return b.substring(delim.length());
		}
		//////////////////////////////////////////////////////////////////////////////////
		private static void start() { if (t == 0) t = millis(); }
		private static void append(StringBuilder b, Object o, String delim) {
			if (o.getClass().isArray()) {
				int len = java.lang.reflect.Array.getLength(o);
				for (int i = 0; i < len; ++i)
					append(b, java.lang.reflect.Array.get(o, i), delim);
			} else if (o instanceof Iterable<?>)
				for (Object p : (Iterable<?>) o)
					append(b, p, delim);
			else {
				if (o instanceof Double)
					o = new java.text.DecimalFormat("#.############").format(o);
				b.append(delim).append(o);
			}
		}
		private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
		private static void print(Object o, Object ... A) { pw.println(build(o, A)); }
		private static void err(Object o, Object ... A) { System.err.println(build(o, A)); }
		private static void exit() {
			IOUtils.pw.close();
			System.out.flush();
			err("------------------");
			err(IOUtils.time());
			System.exit(0);
		}
		private static long t;
		private static long millis() { return System.currentTimeMillis(); }
		private static String time() { return "Time: " + (millis() - t) / 1000.0; }
	}
	public static void main (String[] args) { new C(); IOUtils.exit(); }
}

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

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

class TaskC {
    int[] a;
    public void solve(int testNumber, Reader in, PrintWriter out) {
        int n = in.ni();
        a = new int[n];
        for(int i = 0; i < n; i++) {
            a[i] = in.ni() - 1;
        }
        int max = 1;
        boolean[] used = new boolean[n];
        int[] cycle = new int[n];
        int[] len = new int[n];
        for(int i = 0; i < n; i++) {
            Arrays.fill(used, false);
            int cur = i;
            int edges = 0;
            while(true) {
                if(a[cur] == cur || used[cur]) {
                    cycle[i] = cur;
                    len[i] = edges;
                    break;
                }
                used[cur] = true;
                cur = a[cur];
                edges++;
            }
        }
        for(int i = 0; i < n; i++) {
            max = Math.max(len[i], max);
        }
//        out.println(max);
//        out.println(Arrays.toString(cycle));
        for(int i = 1; i <= max; i++) {
            boolean success = true;
            for(int j = 0; j < n; j++) {
                int leftValue, rightValue;
                leftValue = j;
                rightValue = j;
                for(int z = 0; z < i; z++) {
                    leftValue = a[leftValue];
                }
                for(int z = 0; z < 2 * i; z++) {
                    rightValue = a[rightValue];
                }
                if(leftValue != rightValue) {
                    success = false;
                }
            }
            if(success) {
                out.println(i);
                return;
            }
        }

        int[] cycleLen = new int[n];
        for(int i = 0; i < n; i++) {
            int cur = a[cycle[i]];
            int cnt = 1;
            while(true) {
                if(cur == cycle[i]) {
                    cycleLen[i] = cnt;
                    break;
                }
                cur = a[cur];
                cnt++;
            }
        }

        long lcm = cycleLen[0];
        for(int i = 1; i < n; i++) {
            lcm = Helper.lcm(lcm, cycleLen[i]);
        }

        if(max > lcm) {
            out.println(max % lcm == 0 ? lcm * (max / lcm) : lcm * (max / lcm + 1));
        } else {
            out.println(lcm);
        }

    }
}

class Reader {
    private BufferedReader in;
    private StringTokenizer st = new StringTokenizer("");
    private String delim = " ";

    public Reader(InputStream in) {
        this.in = new BufferedReader(new InputStreamReader(in));
    }

    public String next() {
        if (!st.hasMoreTokens()) {
            st = new StringTokenizer(rl());
        }
        return st.nextToken(delim);
    }

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

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

}

class Helper {

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

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

}

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

public class F {
	FastScanner in;
	PrintWriter out;

	void solve() {
		int n = in.nextInt();
		int[] f = new int[n];
		for (int i = 0; i < n; i++) {
			f[i] = in.nextInt() - 1;
		}
		BigInteger res = BigInteger.ONE;
		int st = 1;
		for (int i = 0; i < n; i++) {
			int[] d = new int[n];
			Arrays.fill(d, -1);
			int cur = i;
			int curd = 0;
			int d0 = -1, d1 = -1;
			while (true) {
				d[cur] = curd;
				curd++;
				cur = f[cur];
				if (d[cur] != -1) {
					d0 = d[cur];
					d1 = curd - d[cur];
					break;
				}
			}
			//System.out.println(d0 + " " + d1);
			st = Math.max(st, d0);
			//System.out.println(x);
			BigInteger g = BigInteger.valueOf(d1).gcd(res);
			res = res.multiply(BigInteger.valueOf(d1)).divide(g);
		}
		BigInteger b = BigInteger.valueOf(st);
		BigInteger ans = b.add(res.add(BigInteger.valueOf(-1))).divide(res).multiply(res);
		out.println(ans);
	}

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

		solve();

		out.close();
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

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

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(in.br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

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

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

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

/**
 * Created by aksenov on 17.04.2015.
 */
public class C2 {
    FastScanner in;
    PrintWriter out;

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

        for (int i = 0; i < p.length; i++) {
            p[i] = in.nextInt() - 1;
        }

        BigInteger ans = BigInteger.ONE;

        int[] color = new int[n];
        int nc = 0;
        int[] cl = new int[n];
        boolean[] failed = new boolean[n];
        int ml = 0;
        for (int i = 0; i < n; i++) {
            if (color[i] != 0)
                continue;
            boolean[] was = new boolean[n];
            int v = i;
            while (!was[v]) {
                was[v] = true;
                v = p[v];
            }

            if (v == i) {
                int u = p[v];
                color[v] = nc + 1;
                cl[nc]++;
                while (u != v) {
                    cl[nc]++;
                    color[u] = nc + 1;
                    u = p[u];
                }

                nc++;
            }
        }
        for (int i = 0; i < n; i++) {
            if (color[i] != 0)
                continue;
            int u = i;
            int l = 0;
            while (color[u] == 0) {
                l++;
                u = p[u];
            }
            ml = Math.max(ml, l);
            failed[color[u] - 1] = true;
        }

        cl = Arrays.copyOf(cl, nc);
        failed = Arrays.copyOf(failed, nc);
        for (int i = 0; i < nc; i++) {
            int c = cl[i];
            BigInteger clen = BigInteger.valueOf(c);
            BigInteger gcd = clen.gcd(ans);
            ans = ans.multiply(clen).divide(gcd);
        }

        BigInteger res = ans;
        while (res.compareTo(BigInteger.valueOf(ml)) < 0) {
            res = res.add(ans);
        }

        out.println(res);
    }

    public void run() {
        try {
            in = new FastScanner();
            out = new PrintWriter(System.out);

            solve();

            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

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

        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());
        }
    }

    public static void main(String[] arg) {
        new C2().run();
    }
}

import java.util.HashMap;
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long min = 1, z = 1;

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

        for (int i = 1; i<=n; i++) {
            HashMap<Integer, Integer> hs = new HashMap();
            hs.put(i, 0);
            int next = a[i];
            int k = 1;
            while (!hs.containsKey(next)) {
                hs.put(next, k);
                k++;
                next = a[next];
            }
            if (next == i) {
                //System.out.println(i + " A " + k);
                z = lcm(z,k);
            } else if ((k = hs.get(next)) > min) {
                //System.out.println(i + " B " + k);
                min = k;
            }
        }
        System.out.println(min%z == 0? min:(min/z+1)*z);
    }

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

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

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

public class CC {

    void solve() {
        int n = nextInt();
        int[] p = new int[n];
        for (int i = 0; i < n; i++) {
            p[i] = nextInt() - 1;
        }
        int[] d = new int[n];
        BigInteger lcm = BigInteger.ONE;
        int maxPred = 0;
        for (int i = 0; i < n; i++) {
            Arrays.fill(d, -1);
            int j = i;
            int len = 0;
            while (d[j] == -1) {
                d[j] = len;
                len++;
                j = p[j];
            }
            int pred = d[j];
            maxPred = Math.max(maxPred, pred);
            int cycle = len - pred;
            lcm = lcm(lcm, BigInteger.valueOf(cycle));
        }
        BigInteger pred = BigInteger.valueOf(maxPred);
        BigInteger ans = lcm;
        while (ans.compareTo(pred) < 0) {
            ans = ans.add(lcm);
        }
        out.println(ans);
    }

    BigInteger lcm(BigInteger a, BigInteger b) {
        return a.multiply(b).divide(a.gcd(b));
    }

    BufferedReader br;
    PrintWriter out;
    StringTokenizer st;

    int nextInt() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                st = new StringTokenizer("-1");
            }
        }
        return Integer.parseInt(st.nextToken());
    }

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

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

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

public class C {

	FastScanner in;
	PrintWriter out;

	void solve() {
		int n = in.nextInt();
		int[] f = new int[n];
		for (int i = 0; i < n; i++) {
			f[i] = in.nextInt() - 1;
		}
		BigInteger ans = BigInteger.ONE, mx = BigInteger.ZERO;

		for (int i = 0; i < n; i++) {
			int[] pos = new int[n];
			Arrays.fill(pos, -1);

			int cur = i;
			for (int j = 0;; j++) {
				if (pos[cur] != -1) {
					int per = j - pos[cur];
					ans = lcm(ans, per);
					mx = mx.max(BigInteger.valueOf(pos[cur]));
					break;
				} else {
					pos[cur] = j;
					cur = f[cur];
				}
			}
		}
		BigInteger ret = ans;
		while (ret.compareTo(mx) < 0) {
			ret = ret.add(ans);
		}
		out.println(ret);
	}

	private BigInteger lcm(BigInteger ans, int pref) {
		if (pref == 0){
			return ans;
		}
		BigInteger b = BigInteger.valueOf(pref);
		return ans.divide(ans.gcd(b)).multiply(b);
	}

	void run() {
		in = new FastScanner();
		out = new PrintWriter(System.out);
		solve();
		out.close();
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

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

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

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

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

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

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

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

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

public class C implements Runnable {
	private static BufferedReader in;
	private static PrintWriter out;
	private static StringTokenizer st;
	private static Random rnd;

	private void solve() throws IOException {
		int numbersCount = nextInt();
		int[] edgeTo = new int[numbersCount];
		for (int i = 0; i < numbersCount; i++) {
			edgeTo[i] = nextInt() - 1;
		}
		long[] a = new long[numbersCount], b = new long[numbersCount];
		int[] lastTime = new int[numbersCount];
		for (int i = 0; i < numbersCount; i++) {
			Arrays.fill(lastTime, -1);
			int u = i;
			int currentTime = 0;
			while (lastTime[u] == -1) {
				lastTime[u] = currentTime;
				u = edgeTo[u];
				++currentTime;
			}
			int currentB = currentTime - lastTime[u];
			int currentA = currentTime - currentB;
			a[i] = currentA;
			b[i] = currentB;
		}
		BigInteger lcm = BigInteger.valueOf(1);
		for (long n : b) {
			BigInteger x = lcm;
			BigInteger y = BigInteger.valueOf(n);
			BigInteger k = x.gcd(y);
			lcm = x.multiply(y).divide(k);
		}
		BigInteger result = lcm;
		while (isSmaller(a, result)) {
			result = result.add(lcm);
		}
		out.println(result);
	}

	private boolean isSmaller(long[] a, BigInteger result) {
		for (long n : a) {
			if (BigInteger.valueOf(n).compareTo(result) > 0) {
				return true;
			}
		}
		return false;
	}

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

	public void run() {
		try {
			final String className = this.getClass().getName().toLowerCase();

			try {
				in = new BufferedReader(new FileReader(className + ".in"));
				out = new PrintWriter(new FileWriter(className + ".out"));
				// in = new BufferedReader(new FileReader("input.txt"));
				// out = new PrintWriter(new FileWriter("output.txt"));
			} catch (FileNotFoundException e) {
				in = new BufferedReader(new InputStreamReader(System.in));
				out = new PrintWriter(System.out);
			}

			rnd = new Random();

			solve();

			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(42);
		}
	}

	private String nextToken() throws IOException {
		while (st == null || !st.hasMoreTokens()) {
			String line = in.readLine();

			if (line == null)
				return null;

			st = new StringTokenizer(line);
		}

		return st.nextToken();
	}

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

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

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

import java.io.Reader;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;

/**
 * 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);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
    public void solve(int testNumber, FastScanner in, FastPrinter out) {
        int n = in.nextInt();
        int[] f = new int[n];
        for (int i = 0; i < n; i++) f[i] = in.nextInt() - 1;
        int[] was = new int[n];
        int[] d = new int[n];
        BigInteger ans = BigInteger.ONE;
        for (int i = 0; i < n; i++) {
            Arrays.fill(was, 0);
            int p = i;
            int c = 0;
            while (was[p] == 0) {
                d[p] = c++;
                was[p] = 1;
                p = f[p];
            }
            BigInteger cycle = BigInteger.valueOf(c - d[p]);
            ans = ans.divide(ans.gcd(cycle)).multiply(cycle);
        }
        for (int q = 1; q <= 2 * n; q++) {
            boolean bad = false;
            for (int i = 0; i < n; i++) {
                int v = i;
                for (int j = 0; j < q; j++) v = f[v];
                int u = v;
                for (int j = 0; j < q; j++) u = f[u];
                if (v != u) {
                    bad = true;
                }
            }
            if (!bad) {
                out.println(q);
                return;
            }
        }
        out.println(ans);
    }
}

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;
        }
    }

}

class FastPrinter extends PrintWriter {

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

}

import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;

import static java.lang.Math.*;

// Solution is at the bottom of code

public class C implements Runnable{

	final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

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

	public static void main(String[] args){
		new Thread(null, new C(), "", 128 * (1L << 20)).start();
	}

	/////////////////////////////////////////////////////////////////////

	void init() throws FileNotFoundException{
		Locale.setDefault(Locale.US);

		if (ONLINE_JUDGE){
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new OutputWriter(System.out);
		}else{
			in = new BufferedReader(new FileReader("input.txt"));
			out = new OutputWriter("output.txt");
		}
	}

	////////////////////////////////////////////////////////////////

	long timeBegin, timeEnd;

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

	void debug(Object... objects){
		if (ONLINE_JUDGE){
			for (Object o: objects){
				System.err.println(o.toString());
			}
		}
	}

	/////////////////////////////////////////////////////////////////////

	public void run(){
		try{
			timeBegin = System.currentTimeMillis();
			Locale.setDefault(Locale.US);

			init();
			solve();

			out.close();
			time();
		}catch (Exception e){
			e.printStackTrace(System.err);
			System.exit(-1);
		}
	}

	/////////////////////////////////////////////////////////////////////

	String delim = " ";

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

		return tok.nextToken(delim);
	}

	String readLine() throws IOException{
		return in.readLine();
	}

	/////////////////////////////////////////////////////////////////

	final char NOT_A_SYMBOL = '\0';

	char readChar() throws IOException{
		int intValue = in.read();

		if (intValue == -1){
			return NOT_A_SYMBOL;
		}

		return (char) intValue;
	}

	char[] readCharArray() throws IOException{
		return readLine().toCharArray();
	}

	/////////////////////////////////////////////////////////////////

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

	int[] readIntArray(int size) throws IOException {
		int[] array = new int[size];

		for (int index = 0; index < size; ++index){
			array[index] = readInt();
		}

		return array;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = readInt();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] readIntArrayWithDecrease(int size) throws IOException {
		int[] array = readIntArray(size);

		for (int i = 0; i < size; ++i) {
			array[i]--;
		}

		return array;
	}

	///////////////////////////////////////////////////////////////////

	int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException {
		int[][] matrix = new int[rowsCount][];

		for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
			matrix[rowIndex] = readIntArray(columnsCount);
		}

		return matrix;
	}

	int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException {
		int[][] matrix = new int[rowsCount][];

		for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
			matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
		}

		return matrix;
	}

	///////////////////////////////////////////////////////////////////

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

	long[] readLongArray(int size) throws IOException{
		long[] array = new long[size];

		for (int index = 0; index < size; ++index){
			array[index] = readLong();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

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

	double[] readDoubleArray(int size) throws IOException{
		double[] array = new double[size];

		for (int index = 0; index < size; ++index){
			array[index] = readDouble();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

	BigInteger readBigInteger() throws IOException {
		return new BigInteger(readString());
	}

	BigDecimal readBigDecimal() throws IOException {
		return new BigDecimal(readString());
	}

	/////////////////////////////////////////////////////////////////////

	Point readPoint() throws IOException{
		int x = readInt();
		int y = readInt();
		return new Point(x, y);
	}

	Point[] readPointArray(int size) throws IOException{
		Point[] array = new Point[size];

		for (int index = 0; index < size; ++index){
			array[index] = readPoint();
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
	throws IOException{
		@SuppressWarnings("unchecked")
		List<Integer>[] graph = new List[vertexNumber];

		for (int index = 0; index < vertexNumber; ++index){
			graph[index] = new ArrayList<Integer>();
		}

		while (edgeNumber-- > 0){
			int from = readInt() - 1;
			int to = readInt() - 1;

			graph[from].add(to);
			graph[to].add(from);
		}

		return graph;
	}

	/////////////////////////////////////////////////////////////////////

	static class IntIndexPair {

		static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() {

			@Override
			public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
				int value1 = indexPair1.value;
				int value2 = indexPair2.value;

				if (value1 != value2) return value1 - value2;

				int index1 = indexPair1.index;
				int index2 = indexPair2.index;

				return index1 - index2;
			}
		};

		static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() {

			@Override
			public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
				int value1 = indexPair1.value;
				int value2 = indexPair2.value;

				if (value1 != value2) return -(value1 - value2);

				int index1 = indexPair1.index;
				int index2 = indexPair2.index;

				return index1 - index2;
			}
		};

		int value, index;

		public IntIndexPair(int value, int index) {
			super();
			this.value = value;
			this.index = index;
		}

		public int getRealIndex() {
			return index + 1;
		}
	}

	IntIndexPair[] readIntIndexArray(int size) throws IOException {
		IntIndexPair[] array = new IntIndexPair[size];

		for (int index = 0; index < size; ++index) {
			array[index] = new IntIndexPair(readInt(), index);
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	static class OutputWriter extends PrintWriter {

		final int DEFAULT_PRECISION = 12;

		protected int precision;
		protected String format, formatWithSpace;

		{
			precision = DEFAULT_PRECISION;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		public OutputWriter(OutputStream out) {
			super(out);
		}

		public OutputWriter(String fileName) throws FileNotFoundException {
			super(fileName);
		}

		public int getPrecision() {
			return precision;
		}

		public void setPrecision(int precision) {
			precision = max(0, precision);
			this.precision = precision;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		private String createFormat(int precision){
			return "%." + precision + "f";
		}

		@Override
		public void print(double d){
			printf(format, d);
		}

		public void printWithSpace(double d){
			printf(formatWithSpace, d);
		}

		public void printAll(double...d){
			for (int i = 0; i < d.length - 1; ++i){
				printWithSpace(d[i]);
			}

			print(d[d.length - 1]);
		}

		@Override
		public void println(double d){
			printlnAll(d);
		}

		public void printlnAll(double... d){
			printAll(d);
			println();
		}
	}

	/////////////////////////////////////////////////////////////////////

	static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
	static final int[][] steps8 = {
			{-1, 0}, {1, 0}, {0, -1}, {0, 1},
			{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
	};

	static final boolean check(int index, int lim){
		return (0 <= index && index < lim);
	}

	/////////////////////////////////////////////////////////////////////

	static final boolean checkBit(int mask, int bit){
		return (mask & (1 << bit)) != 0;
	}

	/////////////////////////////////////////////////////////////////////

	static final long getSum(int[] array) {
		long sum = 0;
		for (int value: array) {
			sum += value;
		}

		return sum;
	}

	static final Point getMinMax(int[] array) {
		int min = array[0];
		int max = array[0];

		for (int index = 0, size = array.length; index < size; ++index, ++index) {
			int value = array[index];

			if (index == size - 1) {
				min = min(min, value);
				max = max(max, value);
			} else {
				int otherValue = array[index + 1];

				if (value <= otherValue) {
					min = min(min, value);
					max = max(max, otherValue);
				} else {
					min = min(min, otherValue);
					max = max(max, value);
				}
			}
		}

		return new Point(min, max);
	}

	/////////////////////////////////////////////////////////////////////

	void solve() throws IOException {
		int n = readInt();
		int[] f = readIntArrayWithDecrease(n);

		int[][] fs = new int[n][3 * n];
		for (int i = 0; i < n; ++i) {
			fs[i][0] = i;
			for (int k = 1; k < 3 * n; ++k) {
				fs[i][k] = f[fs[i][k-1]];
			}
		}

		int[] periods = new int[n];
		int[] starts = new int[n];

		for (int i = 0; i < n; ++i) {
			int[] lasts = new int[n];
			Arrays.fill(lasts, -1);

			for (int j = 0; j < fs[i].length; ++j) {
				if (lasts[fs[i][j]] != -1) {
					starts[i] = lasts[fs[i][j]];
					periods[i] = j - starts[i];
					break;
				} else {
					lasts[fs[i][j]] = j;
				}
//				if (fs[i][j] == fs[i][0]) {
//					periods[i] = j;
//					starts[i] = 0;
//
//					break;
//				}
//
//				if (fs[i][j] == fs[i][j-1]) {
//					periods[i] = 1;
//					starts[i] = j - 1;
//
//					break;
//				}
			}
		}

		long lcmPeriod = periods[0];
		int maxStart = starts[0];

		for (int i = 1; i < n; ++i) {
			lcmPeriod = lcm(lcmPeriod, periods[i]);
			maxStart = max(maxStart, starts[i]);
		}

		long minMultiply = max(1, (maxStart - 1) / lcmPeriod + 1);
		long minPeriod = minMultiply * lcmPeriod;

		out.println(minPeriod);
	}

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

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

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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author unknown
 */
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();
	}
}

class TaskC {
    final int N = 207;

    int n;
    int[] a = new int[N];
    int[] dist = new int[N];

    BigInteger gcd(BigInteger a, BigInteger b) {
        if (a.compareTo(BigInteger.ZERO) == 0) return b;
        return gcd(b.mod(a), a);
    }

    BigInteger lcm(BigInteger a, BigInteger b) {
        return a.divide(gcd(a, b)).multiply(b);
    }

    public void solve(int testNumber, InputReader in, PrintWriter out) {
        n = in.nextInt();
        for (int i = 1; i <= n; ++i) a[i] = in.nextInt();
        int maxi = 0;
        BigInteger ans = BigInteger.ONE;
        for (int i = 1; i <= n; ++i) {
            for (int j = 0; j <= n; ++j) dist[j] = -1;
            dist[i] = 0;
            int j = i;
            int cd = 0;
            while (dist[a[j]] == -1) {
                dist[a[j]] = ++cd;
                j = a[j];
            }
            int len = cd - dist[a[j]] + 1;
            int pre = cd - len + 1;
            maxi = Math.max(maxi, pre);
            ans = lcm(ans, BigInteger.valueOf(len));
        }
        BigInteger tmp = new BigInteger(ans.toString());
        while (ans.compareTo(BigInteger.valueOf(maxi)) == -1) {
            ans = ans.add(tmp);
        }
        out.println(ans);
    }

}

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.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.StringTokenizer;
import java.math.BigInteger;
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);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.readInt();
        int[] a = in.readIntArray(n);
        for (int i = 0; i < n; i++) {
            a[i] --;
        }
        boolean[] onCycle = new boolean[n];
        for (int i = 0; i < n; i++) {
            int cur = i;
            for (int t = 0; t < n; t++) {
                cur = a[cur];
            }
            for (int t = 0; t < n; t++) {
                onCycle[cur] = true;
                cur = a[cur];
            }
        }
        boolean[] used = new boolean[n];
        ArrayList<Integer> length = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (!onCycle[i] || used[i]) {
                continue;
            }
            int cur = a[i], len = 1;
            used[i] = true;
            while (!used[cur]) {
                used[cur] = true;
                len++;
                cur = a[cur];
            }
            length.add(len);
        }
        BigInteger ans = BigInteger.ONE;
        for (int i : length) {
            BigInteger g = ans.gcd(BigInteger.valueOf(i));
            ans = ans.multiply(BigInteger.valueOf(i)).divide(g);
        }
        int max = 0;
        for (int i = 0; i < n; i++) {
            int count = 0, cur = i;
            while (!onCycle[cur]) {
                cur = a[cur];
                count++;
            }
            max = Math.max(max, count);
        }
        BigInteger realAns = ans;
        while (realAns.compareTo(BigInteger.valueOf(max)) < 0) {
            realAns = realAns.add(ans);
        }
        out.printf("%d\n", realAns);
    }
}

class InputReader {
    private BufferedReader reader;
    private StringTokenizer tokenizer;

    public InputReader(BufferedReader reader) {
        this.reader = reader;
    }

    public InputReader(Reader reader) {
        this(new BufferedReader(reader));
    }

    public InputReader(InputStream stream) {
        this(new InputStreamReader(stream));
    }

    private String nextLine() {
        String result;
        try {
            result = reader.readLine();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
        return result;
    }

    public String readWord() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(nextLine());
        }
        return tokenizer.nextToken();
    }

    public int readInt() {
        return Integer.parseInt(readWord());
    }

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

}

class OutputWriter {
    private PrintWriter writer;

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

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

    public OutputWriter(OutputStream stream) {
        this(new OutputStreamWriter(stream));
    }

    public void printf(String format, Object...args) {
        writer.printf(format, args);
    }

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

import javafx.geometry.Pos;
import javafx.util.Pair;

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.security.cert.PolicyNode;
import java.util.*;

public class Solution {
    BufferedReader in;
    PrintWriter out;
    StringTokenizer st;

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

    final int inf = Integer.MAX_VALUE / 2;
    final double eps = 0.0000000001;

    int rd() throws IOException {
        return Integer.parseInt(nextToken());
    }
    double rdd() throws IOException {
        return Double.parseDouble(nextToken());
    }
    long rdl() throws IOException {
        return Long.parseLong(nextToken());
    }

    int n;
    int[] a;

    int[] f(int[] x, int[] a){
        int[] r = new int[n];
        for (int i = 0; i < n; i++) r[i] = a[x[i]];
        return r;
    }

    boolean neq(int[] a, int[] b) {
        for (int i = 0; i < n; i++)
            if (a[i] != b[i]) return true;
        return false;
    }

    void solve() throws IOException {
        n = rd();
        a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = rd() - 1;
        }
        BigInteger ans = BigInteger.ONE;
        long ppmax = 0;
        for (int i = 0; i < n; i++) {
                int j1 = i;
                for (int j = 0; j < 300; j++) j1 = a[j1];
                int j2 = a[j1];
                int cnt = 1;
                while (j1 != j2) {
                    cnt++;
                    j1 = a[j1];
                    j2 = a[a[j2]];
                }
                ans = ans.multiply(BigInteger.valueOf(cnt)).divide(ans.gcd(BigInteger.valueOf(cnt)));
                j1 = i;
                j2 = i;
                for (int j = 0; j < cnt; j++) j2 = a[j2];
                int pp = 0;
                while (j1 != j2) {
                    pp++;
                    j1 = a[j1];
                    j2 = a[j2];
                }
                ppmax = Math.max(ppmax, pp);
                j1 = i;
        }
        BigInteger p = BigInteger.valueOf(ppmax);
        if (p.remainder(ans).equals(BigInteger.ZERO))
            out.println(ppmax == 0 ? ans : p);
        else
            out.println(p.add(ans.subtract(p.remainder(ans))));
    }

    void run() throws IOException {
        try {
//            in = new BufferedReader(new FileReader("notation.in"));
//            out = new PrintWriter("notation.out");
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
            Locale.setDefault(Locale.UK);
            solve();
        } catch (Exception e) {
            e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
        } finally {
            out.close();
        }
    }

    public static void main(String Args[]) throws IOException {
        new Solution().run();
    }
}

import java.awt.*;
import java.io.*;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;

import static java.lang.Math.max;

public class C {

    final static Random random = new Random();

    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[] a = readArr(n);
        boolean[] inCycle = new boolean[n];
        for(int i = 0; i < n; i++) {
            int tmp = i;
            for(int j = 0; j < 300; j++) {
                tmp = a[tmp];
                if(tmp == i) {
                    inCycle[i] = true;
                }
            }
        }
        Set<Integer> x = new HashSet<Integer>();
        int[] size = new int[n];
        boolean[] used = new boolean[n];
        for(int i = 0; i < n; i++) {
            if(!inCycle[i]) continue;
            if(used[i]) continue;
            int count = 0;
            int tmp = i;
            used[i] = true;
            for(int j = 0; j < 300; j++) {
                tmp = a[tmp];
                count++;
                if(tmp == i) {
                    break;
                }
                used[tmp] = true;
            }
            x.add(count);
            size[i] = count;
            for(int j = 0; j < 300; j++) {
                tmp = a[tmp];
                if(tmp == i) {
                    break;
                }
                size[tmp] = count;
            }
        }

        int maxStep = 0;
        for(int i = 0; i < n; i++) {
            if(!inCycle[i]) {
                int tmp = i;
                int step = 0;
                while (true) {
                    step++;
                    tmp = a[tmp];
                    if(inCycle[tmp]) {
                        break;
                    }
                }
                while (step % size[tmp] != 0) {
                    step++;
                }
                size[i] = step;
                maxStep = max(maxStep, step);
            }

        }

        long lcm = 1;
        for(int len: x) {
            lcm = lcm(lcm, len);
        }
        long res = lcm;
        while (res < maxStep) {
            res += lcm;
        }
        out.println(res);
    }

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

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

    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 {
        n = max(n, 0);

        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = readInt() - 1;
        }
        return res;
    }

    int[] readIntArray(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;
    }

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

    Point readPoint() throws IOException {
        return new Point(readInt(), readInt());
    }

    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.io.*;
import java.math.*;
import java.util.*;

public class Main {
    BigInteger lcm(BigInteger a, BigInteger b) {
        BigInteger g = a.gcd(b);
        return a.divide(g).multiply(b);
    }

    public void run() {
        int n = reader.nextInt();
        int[][] go = new int[n + 1][n];
        for (int i = 0; i < n; ++ i) {
            go[0][i] = i;
            go[1][i] = reader.nextInt() - 1;
        }
        for (int j = 2; j <= n; ++ j) {
            for (int i = 0; i < n; ++ i) {
                go[j][i] = go[1][go[j - 1][i]];
            }
        }
        int[] cycle = new int[n];
        for (int i = 0; i < n; ++ i) {
            cycle[i] = 1;
            while (cycle[i] <= n && go[cycle[i]][i] != i) {
                cycle[i] ++;
            }
        }
        BigInteger l = BigInteger.ONE;
        for (int i = 0; i < n; ++ i) {
            if (cycle[i] <= n) {
                l = lcm(l, BigInteger.valueOf(cycle[i]));
            }
        }
        BigInteger result = l;
        for (int i = 0; i < n; ++ i) {
            int j = 0;
            while (cycle[go[j][i]] > n) {
                j ++;
            }
            while (BigInteger.valueOf(j).compareTo(result) > 0) {
                result = result.add(l);
            }
        }
        writer.println(result);
        writer.close();
    }

    Main() {
        reader = new InputReader(System.in);
        writer = new PrintWriter(System.out);
    }

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

    private static void debug(Object...os) {
        System.err.println(Arrays.deepToString(os));
    }

    private InputReader reader;
    private PrintWriter writer;
}

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

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

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

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

    private InputStream stream;
    private int head, charCount;
    private byte[] buffer = new byte[1024];
}

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

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

class TaskC {

    int[] f;
    boolean[] used;
    int[] cycleLength;

    int dfs(int v, int start, int len) {
        if (f[v] == start)
            return len + 1;
        if (used[f[v]])
            return 0;
        used[v] = true;
        return dfs(f[v], start, len + 1);
    }

    public void solve(int testNumber, FastScanner in, PrintWriter out) {
        int n = in.nextInt();
        f = new int[n];
        for (int i = 0; i < n; i++)
            f[i] = in.nextInt() - 1;
        used = new boolean[n];
        cycleLength = new int[n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(used, false);
            cycleLength[i] = dfs(i, i, 0);
        }
        int low = 0;
        for (int i = 0; i < n; i++) {
            int v = i;
            int cur = 0;
            while (cycleLength[v] == 0) {
                cur++;
                v = f[v];
            }
            low = Math.max(low, cur);
        }
        TreeSet<Integer> all = new TreeSet<>();
        for (int i = 0; i < n; i++)
            if (cycleLength[i] >= 2)
                all.add(cycleLength[i]);
        BigInteger lcm = BigInteger.ONE;
        for (int elem : all)
            lcm = lcm.divide(lcm.gcd(BigInteger.valueOf(elem))).multiply(BigInteger.valueOf(elem));
        BigInteger sol = lcm;
        while (sol.compareTo(BigInteger.valueOf(low)) < 0)
            sol = sol.add(lcm);
        out.println(sol);
    }
}

class FastScanner {
    private StringTokenizer tokenizer;
    private BufferedReader reader;

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

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

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

}

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

public class IdempotentFunctions {

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

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

	public static void main(String[] args) throws IOException {
		MyScanner sc = new MyScanner(System.in);
		PrintWriter out = new PrintWriter(System.out);
		int n = sc.nextInt();
		int[] f = new int[n];
		for (int i = 0; i < n; ++i) {
			f[i] = sc.nextInt() - 1;
		}
		int maxDistanceToCycle = 0;
		long lcm = 1;
		for (int i = 0; i < n; ++i) {
			int[] time = new int[n];
			int current = i;
			int currentTime = 1;
			while (time[current] == 0) {
				time[current] = currentTime++;
				current = f[current];
			}
			int cycleLength = currentTime - time[current];
			int distToCycle = time[current] - 1;
			maxDistanceToCycle = Math.max(maxDistanceToCycle, distToCycle);
			lcm = lcm(lcm, cycleLength);
		}
		long ans = lcm;
		while (ans < maxDistanceToCycle)
			ans += lcm;
		out.println(ans);
		out.flush();
		out.close();
	}

	static class MyScanner {
		StringTokenizer st;
		BufferedReader br;

		public MyScanner(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 boolean ready() throws IOException {
			return br.ready();
		}
	}
}

import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Map.Entry;

import static java.lang.Math.*;

public class C extends PrintWriter {

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

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

	void run() {
		int n = nextInt();
		int[] p = new int[n];

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

		int[] a = new int[n], b = new int[n];

		for (int i = 0; i < n; i++) {
			boolean[] c = new boolean[n];

			int v = i;

			while (!c[v]) {
				c[v] = true;
				v = p[v];
				++a[i];
			}

			int u = v;
			v = p[v];

			while (v != u) {
				v = p[v];
				++b[i];
				--a[i];
			}

			--a[i];
			++b[i];
		}

		long lcm = 1, m = 0;

		for (int v : b) {
			lcm = lcm(lcm, v);
		}

		for (int v : a) {
			m = max(m, v);
		}

		if (lcm < m) {
			long k = (m + lcm - 1) / lcm;
			lcm *= k;
		}

		println(lcm);

	}

	int[][] nextMatrix(int n, int m) {
		int[][] matrix = new int[n][m];
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++)
				matrix[i][j] = nextInt();
		return matrix;
	}

	String next() {
		while (!tokenizer.hasMoreTokens())
			tokenizer = new StringTokenizer(nextLine());
		return tokenizer.nextToken();
	}

	boolean hasNext() {
		while (!tokenizer.hasMoreTokens()) {
			String line = nextLine();
			if (line == null) {
				return false;
			}
			tokenizer = new StringTokenizer(line);
		}
		return true;
	}

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

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

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

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

	String nextLine() {
		try {
			return reader.readLine();
		} catch (IOException err) {
			return null;
		}
	}

	public C(OutputStream outputStream) {
		super(outputStream);
	}

	static BufferedReader reader;
	static StringTokenizer tokenizer = new StringTokenizer("");
	static Random rnd = new Random();
	static boolean OJ;

	public static void main(String[] args) throws IOException {
		OJ = System.getProperty("ONLINE_JUDGE") != null;
		C solution = new C(System.out);
		if (OJ) {
			reader = new BufferedReader(new InputStreamReader(System.in));
			solution.run();
		} else {
			reader = new BufferedReader(new FileReader(new File(C.class.getName() + ".txt")));
			long timeout = System.currentTimeMillis();
			while (solution.hasNext()) {
				solution.run();
				solution.println();
				solution.println("----------------------------------");
			}
			solution.println("time: " + (System.currentTimeMillis() - timeout));
		}
		solution.close();
		reader.close();
	}
}

import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class A {
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        // Scanner scan = new Scanner(System.in);
        // PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(bf.readLine());
        StringTokenizer st = new StringTokenizer(bf.readLine());
        int[][] a = new int[401][n];
        for(int i=0; i<n; i++) a[0][i] = i+1;
        for(int i=0; i<n; i++) a[1][i] = Integer.parseInt(st.nextToken());
        int[] b = new int[n];
        for(int i=0; i<n; i++) {
            int counter = 1;
            int val = i;
            while(a[1][val]-1 != i) {
                counter++;
                val = a[1][val]-1;
                if(counter > 400) {
                    counter = 1007;
                    break;
                }
            }
            b[i] = counter;
        }
        long[] ans = new long[401];
        for(int i=0; i<401; i++) ans[i] = i;
         for(int i=1; i<=400; i++)
            for(int j=0; j<n; j++)
                a[i][j] = a[1][a[i-1][j]-1];
        long min = Long.MAX_VALUE;
        for(int i=1; i<=400; i++) {
            for(int j=0; j<n; j++) {
                //System.out.println(n + " " + i + " " + j + " " + a[i-1][j]);
                ans[i] = lcm(ans[i], b[a[i][j]-1]);
            }
            if(ans[i] < min) min = ans[i];
        }
        System.out.println(min);
        // int n = Integer.parseInt(st.nextToken());
        // int n = scan.nextInt();

        // out.close(); System.exit(0);
    }
    public static long gcd(long a, long b) {
        if(b == 0) return a;
        return gcd(b, a % b);
    }
    public static long lcm(long a, long b) {
        return ((1L*a*b)/gcd(a, b));
    }
}

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

@SuppressWarnings("unchecked")

public class Main implements Runnable {

    public static final String FILENAME = null;

    final int maxn = 210;
    int p[] = new int[maxn];
    int mark[] = new int[maxn];

    private void solve() throws IOException {
        int n = nextInt();
        for (int i = 0; i < n; ++i) p[i] = nextInt() - 1;
        int min = 1;
        BigInteger del = BigInteger.ONE;
        for (int i = 0; i < n; ++i) if (mark[i] == 0)
        {
            int x = i;
            int cnt = 0;
            int cc = 0;
            while (true)
            {
                mark[x] = ++cnt;
                if (mark[p[x]] == 0)
                {
                    x = p[x];
                }
                else if (mark[p[x]] > 0)
                {
                    min = Math.max(min, mark[p[x]] - 1);
                    BigInteger cyc = BigInteger.valueOf(mark[x] - mark[p[x]] + 1);
                    del = del.multiply(cyc).divide(del.gcd(cyc));
                    cc = mark[p[x]];
                    break;
                }
                else
                {
                    min = Math.max(min, mark[x] - 1 - mark[p[x]]);
                    cc = mark[x] - mark[p[x]];
                    break;
                }

            }
            x = i;
            cnt = 0;
            while (true)
            {
                mark[x] = Math.min(-1, (++cnt) - cc - 1);
                if (mark[p[x]] != -1) x = p[x];
                else break;
            }
        }
        BigInteger res = del;
        while (res.compareTo(BigInteger.valueOf(min)) < 0) res = res.add(del);
        out.println(res);

    }
    // -----------------------------------------------
    private BufferedReader br;
    private StringTokenizer _st;
    private PrintWriter out;

    private void myAssert(boolean assertion) {
        if (!assertion) throw new AssertionError();
    }
    private void dbg(Object...os){
        System.err.println(Arrays.deepToString(os));
        System.err.flush();
    }
    private String next() throws IOException {
        while (_st == null || !_st.hasMoreTokens()) {
            String s = br.readLine();
            if (s == null) return null;
            _st = new StringTokenizer(s);
        }
        return _st.nextToken();
    }
    private int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
    private long nextLong() throws IOException {
        return Long.parseLong(next());
    }
    private double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
    private String nextLine() throws IOException {
        _st = null;
        return br.readLine();
    }
    public void run() {
        long startTime = System.nanoTime();
        try {
            if (FILENAME == null) {
                br = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                br = new BufferedReader(new FileReader(FILENAME + ".in"));
                out = new PrintWriter(FILENAME + ".out");
            }
            try {
                solve();
            } finally {
                out.close();
            }
        } catch (IOException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
        }
        long finishTime = System.nanoTime();
//      System.err.printf("Time = %.3f\n", (finishTime - startTime) / 1e9);
    }
    public static void main(String[] args) {
        new Thread(new Main()).start();
    }

}

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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Vadim
 */
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();
	}
}

class TaskC {

    private long gcd (long a, long b) {
        while (b != 0) {
            a %= b;
            long t = a;
            a = b;
            b = t;
        }
        return a;
    }

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

    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.ni();
        int[] df = new int[n];

        for (int i = 0; i < n; i++) {
            df[i] = in.ni() - 1;
        }
        int [] cycles = new int[n];
        int [] routes = new int[n];
        int[] length = new int[n];
        for (int i = 0; i < n; i++) {
            int[] flag = new int[n];
            int x = i;
            int k = 0;
            while(flag[x] == 0) {
                flag[x] = 1;
                x = df[x];
                k++;
            }
            if(x == i) {
                cycles[i] = k;
            } else {
                routes [i] = x;
                length [i] = k;
            }
        }
        for (int i = 0; i < n; i++) {
            if(cycles[i] == 0) {
                length [i] = length [i] - cycles[routes[i]];
            }
        }

        TreeSet<Integer> numbers = new TreeSet<Integer>();
        for (int i = 0; i < n; i++) {
            if(cycles[i] != 0) {
                numbers.add(cycles[i]);
            }
        }
        long lcm = 1;
        for (Integer number : numbers) {
            lcm = lcm(lcm, number);
        }
        long res = lcm;
        for (int i = 0; i < n; i++) {
            if(length[i] != 0) {
                if(length[i] > res) {
                    long l = (length[i]/lcm)*lcm;
                    if(l < length[i]) {
                        l += lcm;
                    }
                    res = Math.max(l, res);
                }
            }
        }
        out.println(res);
    }
}

class InputReader extends BufferedReader {
    public InputReader(InputStream st) {
        super(new InputStreamReader(st));
    }

    public String readLine() {
        try {
            return super.readLine();
        } catch (IOException e) {
            return null;
        }
    }

    private int readByte() {
        try {
            return read();
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    public 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();
        }
    }

}

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

/**
 * Created by pva701 on 2/26/15.
 */

public class Main {
    public static final String TASK = "matrix";
    public static final int INF = 1000000000;
    public static final int K = 30;

    PrintWriter out;

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

    BigInteger toBI(int cur) {
        return BigInteger.valueOf((long)cur);
    }

    public void solve() throws IOException {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] f = new int[n];
        for (int i = 0; i < n; ++i) {
            int x = in.nextInt();
            f[i] = x - 1;
        }

        BigInteger res = BigInteger.ONE;
        int[] a = new int[n];
        int[] b = new int[n];
        for (int i = 0; i < n; ++i) {
            int len = 0;
            int[] use = new int[n];
            int x = i;
            while (use[x] == 0) {
                use[x] = ++len;
                x = f[x];
                //System.out.println(i + " " + x);
            }

            int cur = len + 1 - use[x];
            b[i] = use[x] - 1;
            a[i] = cur;
            res = res.multiply(toBI(cur)).divide(res.gcd(toBI(cur)));
        }
        BigInteger r = res;
        while (true) {
            boolean fail = false;
            for (int i = 0; i < n && !fail; ++i)
                if (toBI(b[i]).compareTo(res) > 0) fail = true;
            if (!fail) break;
            res = res.add(r);
        }
        System.out.println(res.toString());

    }

    public void run() {
        try {
            //in = new FastScanner(new File(TASK + ".in"));
            out = new PrintWriter(new File(TASK + ".out"));
            long l = System.currentTimeMillis();
            solve();
            long r = System.currentTimeMillis();
            System.err.println("time = " + (r - l) / 1000.0);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

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

        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());
        }
    }
}

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

public class VKr3qA {

	static int n;
	static int f[],distToCycle[];
	static boolean vis[],inCycle[],inStack[];
	static ArrayList<Integer> cycleLengths;

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    PrintWriter w = new PrintWriter(System.out);

	    n = ip(br.readLine());

	    StringTokenizer st2 = new StringTokenizer(br.readLine());
	    f = new int[n];
	    for(int i=0;i<n;i++)
	    	f[i] = ip(st2.nextToken()) - 1;

	    vis = new boolean[n];
	    inCycle = new boolean[n];
	    inStack = new boolean[n];
	    cycleLengths = new ArrayList<Integer>();

	    for(int i=0;i<n;i++){
	    	if(!vis[i]){
	    		vis[i] = true;
	    		dfs1(i);
	    	}
	    }

	    distToCycle = new int[n];
	    Arrays.fill(distToCycle, -1);
	    for(int i=0;i<n;i++)
	    	if(distToCycle[i] == -1)	dfs2(i);

	    long lcm = 1;
	    for(int x : cycleLengths)
	    	lcm = lcm(lcm,x);

	    long ans = lcm;
	    for(int i=0;i<n;i++)
	    	while(ans < distToCycle[i])
	    		ans += lcm;

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

	public static void dfs1(int curr){
		inStack[curr] = true;
		if(!vis[f[curr]]){
			vis[f[curr]] = true;
			dfs1(f[curr]);
		}
		else{
			if(!inCycle[f[curr]] && inStack[f[curr]]){
				int root = f[curr],cycleLength=1;
				inCycle[curr] = true;
				while(root != curr){
					inCycle[root] = true;
					cycleLength++;
					root = f[root];
				}
				cycleLengths.add(cycleLength);
			}
		}
		inStack[curr] = false;
	}

	public static int dfs2(int curr){
		if(distToCycle[curr] == -1){
			if(inCycle[curr])
				distToCycle[curr] = 0;
			else
				distToCycle[curr] = 1 + dfs2(f[curr]);
		}
		return distToCycle[curr];
	}

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

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

	public static int ip(String s){
		return Integer.parseInt(s);
	}

}

import java.util.*;
public class c {
public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    //int n = 50;
    int[] f = new int[n+1];
    //Random r = new Random();
    //for(int i = 1; i<=n; i++) f[i] = r.nextInt(n)+1;
    //System.out.println(Arrays.toString(f));
    //System.out.println(n);
    //for(int x : f) System.out.print(x+" ");
    //System.out.println();
    for(int i = 1; i<=n; i++) f[i] = input.nextInt();
    int[] g = new int[n+1];
    for(int i = 0; i<=n; i++) g[i] = f[i];
    int res = 1;
    int[] cycles = new int[n+1];
    int[] off = new int[n+1];
    for(int i = 1; i<=n; i++)
    {
        cycles[i] = 0;
        int at = i;
        int[] last = new int[n+1];
        Arrays.fill(last, -1);
        int ctr = 0;
        last[i] = 0;
        while(true)
        {
            at = f[at];
            ctr++;
            if(last[at] != -1)
            {
                off[i] = last[at];
                cycles[i] = ctr - last[at];
                break;
            }
            last[at] = ctr;
        }
    }
    //System.out.println(Arrays.toString(cycles)+" "+Arrays.toString(off));
    long lcm = 1;
    for(int i = 1; i<=n; i++)
    {
        lcm = lcm(lcm, cycles[i]);
    }
    long ans = lcm;
    for(int i = 1; i<=n; i++) lcm = Math.max(lcm, off[i]);
    //System.out.println(ans+" "+lcm);
    long output = lcm / ans * ans;
    //System.out.println(output+" "+lcm+" "+ans);
    while(output < lcm) output += ans;
    System.out.println(output);
//  while(true)
//  {
//      boolean valid = true;
//      for(int i = 1; i<=n; i++) if(g[g[i]] != g[i])
//      {
//          valid = false;
//          break;
//      }
//      if(valid)
//      {
//          System.out.println(res);
//          break;
//      }
//      res++;
//      for(int i = 1; i<=n; i++) g[i] = f[g[i]];
//  }
    //System.out.println(res);
}
static long gcd(long a, long b)
{
    return b == 0 ? a : gcd(b, a%b);
}
static long lcm(long a, long b)
{
    return a / gcd(a, b) * b;
}
}

import java.util.*;
public class IdempotentFunctions
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);

		int n = in.nextInt();

		int[] adj = new int[n];
		for(int x = 0; x < n; x++)
		{
			adj[x] = in.nextInt() - 1;
		}

		boolean[] cycle = new boolean[n];
		for(int y = 0; y < adj.length; y++)
		{
			boolean[] visited = new boolean[adj.length];
			visited[y] = true;

			int node = adj[y];
			while(!visited[node])
			{
				visited[node] = true;
				node = adj[node];
			}

			if(node == y)
			{
				cycle[y] = true;
			}
		}

		int max = 1;
		for(int z = 0; z < adj.length; z++)
		{
			int node = z;
			int current = 0;
			while(!cycle[node])
			{
				node = adj[node];
				current++;
			}

			max = Math.max(max, current);
		}

		boolean[] visited = new boolean[adj.length];
		long cycleSize = 1;
		for(int a = 0; a < adj.length; a++)
		{
			if(cycle[a])
			{
				int node = adj[a];
				int size = 1;
				while(node != a)
				{
					node = adj[node];
					size++;
				}

				cycleSize = lcm(cycleSize, size);
			}
		}

		System.out.println(((max + cycleSize - 1) / cycleSize) * cycleSize);
	}

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

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

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Scanner;

public class C {

    static void solve() throws IOException {
        int n = in.nextInt();
        int[] f = new int[n];
        for ( int i = 0; i < n;i ++ ) {
            f[i] = in.nextInt() - 1;
        }
        BigInteger p = BigInteger.ONE;
        boolean[] cycle = new boolean[n];
        for ( int i = 0; i < n; i ++ ) {
            int[] pos = new int[n];
            for ( int j = 1, c = i; ; j ++, c = f[c] ) {
                if ( pos[c] > 0 ) {
                    BigInteger l = BigInteger.valueOf( j - pos[c] );
                    p = p.divide( p.gcd( l ) ).multiply( l );
                    for ( int k = 0; k < n; k ++ ) {
                        if ( pos[k] >= pos[c] ) {
                            cycle[k] = true;
                        }
                    }
                    break;
                }
                pos[c] = j;
            }
        }
        int maxD = 0;
        for ( int i = 0; i < n; i ++ ) {
            int d = 0;
            int c = i;
            while ( ! cycle[c] ) {
                d ++;
                c = f[c];
            }
            maxD = Math.max( maxD, d );
        }
        long t = p.longValue();
        long r = t;
        while ( r < maxD ) {
            r += t;
        }
        out.println( r );
    }

    static Scanner in;
//    static StreamTokenizer in;
    static PrintWriter out;

//    static int nextInt() throws IOException {
//        in.nextToken();
//        return ( int ) in.nval;
//    }

    public static void main( String[] args ) throws IOException {
        in = new Scanner( System.in );
//        in = new StreamTokenizer( new InputStreamReader( System.in ) );
        out = new PrintWriter( System.out );
        solve();
        out.close();
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) throws IOException {
		new Thread(null, new Runnable() {
			public void run() {
				try {
					long prevTime = System.currentTimeMillis();
					new Main().run();
					System.err.println("Total time: "
							+ (System.currentTimeMillis() - prevTime) + " ms");
					System.err.println("Memory status: " + memoryStatus());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}, "1", 1L << 24).start();
	}

	void run() throws IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		Object o = solve();
		if (o != null)
			out.println(o);
		out.close();
		in.close();
	}

	private Object solve() throws IOException {
		int n = ni();
		int[] arr = nia(n);
		for(int i =0;i<n;i++)
			arr[i]--;

		int least =0;
		long cycle = 1;
		for(int i =0;i<n;i++){
			int[] pair = go(arr, i);
			least = Math.max(least, pair[0]);
			cycle = mcm(cycle, pair[1]);
		}

		long coef =1;
		while(coef * cycle < least)
			coef++;
		return coef * cycle;
	}

	private long mcm(long a, long b) {
		return (a*b) / gcd(Math.min(a, b), Math.max(a, b));
	}

	private long gcd(long min, long max) {
		if(min==0)
			return max;
		return gcd(max%min, min);
	}

	private int[] go(int[] arr, int u) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(u);

		Set<Integer> set = new HashSet<Integer>();
		set.add(u);

		while(!set.contains(arr[u])){
			u = arr[u];
			set.add(u);
			list.add(u);
		}
		int index = list.indexOf(arr[u]);
		int len = list.size() - index;
		return new int[]{index, len};
	}

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

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

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

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

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

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

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

	double[] nda(int size) throws IOException {
		double[] ret = new double[size];
		for (int i = 0; i < size; i++)
			ret[i] = nd();
		return ret;
	}

	String nextLine() throws IOException {
		strTok = new StringTokenizer("");
		return in.readLine();
	}

	boolean EOF() throws IOException {
		while (!strTok.hasMoreTokens()) {
			String s = in.readLine();
			if (s == null)
				return true;
			strTok = new StringTokenizer(s);
		}
		return false;
	}

	void printRepeat(String s, int count) {
		for (int i = 0; i < count; i++)
			out.print(s);
	}

	void printArray(int[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0)
				out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(long[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0)
				out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(double[] array) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0)
				out.print(' ');
			out.print(array[i]);
		}
		out.println();
	}

	void printArray(double[] array, String spec) {
		for (int i = 0; i < array.length; i++) {
			if (i > 0)
				out.print(' ');
			out.printf(Locale.US, spec, array[i]);
		}
		out.println();
	}

	void printArray(Object[] array) {
		boolean blank = false;
		for (Object x : array) {
			if (blank)
				out.print(' ');
			else
				blank = true;
			out.print(x);
		}
		out.println();
	}

	@SuppressWarnings("rawtypes")
	void printCollection(Collection collection) {
		boolean blank = false;
		for (Object x : collection) {
			if (blank)
				out.print(' ');
			else
				blank = true;
			out.print(x);
		}
		out.println();
	}

	static String memoryStatus() {
		return (Runtime.getRuntime().totalMemory()
				- Runtime.getRuntime().freeMemory() >> 20)
				+ "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB";
	}

	public void pln() {
		out.println();
	}

	public void pln(int arg) {
		out.println(arg);
	}

	public void pln(long arg) {
		out.println(arg);
	}

	public void pln(double arg) {
		out.println(arg);
	}

	public void pln(String arg) {
		out.println(arg);
	}

	public void pln(boolean arg) {
		out.println(arg);
	}

	public void pln(char arg) {
		out.println(arg);
	}

	public void pln(float arg) {
		out.println(arg);
	}

	public void pln(Object arg) {
		out.println(arg);
	}

	public void p(int arg) {
		out.print(arg);
	}

	public void p(long arg) {
		out.print(arg);
	}

	public void p(double arg) {
		out.print(arg);
	}

	public void p(String arg) {
		out.print(arg);
	}

	public void p(boolean arg) {
		out.print(arg);
	}

	public void p(char arg) {
		out.print(arg);
	}

	public void p(float arg) {
		out.print(arg);
	}

	public void p(Object arg) {
		out.print(arg);
	}

}

//package vk2015.r3;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class C {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		int[] f = na(n);
		for(int i = 0;i < n;i++){
			f[i]--;
		}
		long c = 1;
		long maxtail = 1;
		for(int i = 0;i < n;i++){
			int x = i;
			int[] when = new int[n];
			Arrays.fill(when, -1);
			int tail = 0, cycle = 0;
			for(int t = 0;;t++){
				if(when[x] == -1){
					when[x] = t;
					x = f[x];
				}else{
					tail = when[x];
					maxtail = Math.max(maxtail, tail);
					cycle = t-when[x];
					c = c / gcd(c, cycle) * cycle;
					break;
				}
			}
		}
		long ret = (maxtail+c-1)/c*c;
		out.println(ret);
	}

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

	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 C().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.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Vector;

public class C {
	public static final boolean DEBUG = false;
	String filename = "";
	Scanner sc;
	PrintWriter pw;
	public void debug(Object o) {
		if (DEBUG) {
			int ln = Thread.currentThread().getStackTrace()[2].getLineNumber();
			String fn = Thread.currentThread().getStackTrace()[2].getFileName();
			System.out.println("(" + fn + ":" + ln + "): " + o);
		}
	}

	public void pln(Object o) {
		System.out.println(o);
	}

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

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

	public void run() throws FileNotFoundException {
		if (filename.isEmpty()) {
			sc = new Scanner(System.in);
			pw = new PrintWriter(System.out);
		}
		else {
			sc = new Scanner(new File(filename + ".in"));
			pw = new PrintWriter(new File(filename + ".out"));
		}
		int n = sc.nextInt();
		int[] p = new int[n];
		for (int i=0; i<n; i++) {
			p[i] = sc.nextInt() - 1;
		}

		long result = 1;
		long minResult = 1;
		for (int i=0; i<n; i++) {
			int crt = i;
			int[] seen = new int[n];
			for (int it=1; ; it++) {
				crt = p[crt];
				if (crt == i) {
					result = lcm(result, it);
					break;
				}
				if (seen[crt] > 0) {
					minResult = Math.max(minResult, seen[crt]);
					break;
				}
				seen[crt] = it;
			}
		}

		long result0 = result;
		while (result < minResult) {
			result += result0;
		}

		pln(result);
	}

	public static void main(String[] args) {
		C t = new C();
		try {
			t.run();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}

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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author George Marcus
 */
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();
	}
}

class TaskC {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int N = in.nextInt();
        int[] f = new int[N + 1];
        for (int i = 1; i <= N; i++) {
            f[i] = in.nextInt();
        }

        int[] C = new int[N + 1];
        Arrays.fill(C, -1);
        int[] F = new int[N + 1];
        int[] nf = new int[N + 1];
        System.arraycopy(f, 0, F, 0, N + 1);
        for (int k = 1; k <= N + 1; k++) {
            for (int x = 1; x <= N; x++) {
                if (F[x] == x) {
                    if (C[x] == -1) {
                        C[x] = k;
                    }
                }
            }
            for (int x = 1; x <= N; x++) {
                nf[x] = f[F[x]];
            }
            System.arraycopy(nf, 0, F, 0, N + 1);
        }

        int[] D = new int[N + 1];
        System.arraycopy(f, 0, F, 0, N + 1);
        Arrays.fill(D, -1);
        for (int k = 1; k <= N + 1; k++) {
            for (int x = 1; x <= N; x++) {
                if (D[x] == -1 && C[x] == -1 && C[F[x]] != -1) {
                    D[x] = k;
                }
            }
            for (int x = 1; x <= N; x++) {
                nf[x] = f[F[x]];
            }
            System.arraycopy(nf, 0, F, 0, N + 1);
        }

        long K = 1;
        for (int x = 1; x <= N; x++) {
            if (C[x] != -1) {
                K = lcm(K, C[x]);
            }
        }

        int maxD = 0;
        for (int x = 1; x <= N; x++) {
            if (D[x] != -1) {
                maxD = Math.max(maxD, D[x]);
            }
        }

        long ans = K;
        while (ans < maxD) {
            ans += K;
        }

        out.println(ans);
    }

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

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

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 nextInt() {
        return Integer.parseInt(nextString());
    }

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

        return res.toString();
    }

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

}

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

public class F {
	FastScanner in;
	PrintWriter out;

	void solve() {
		int n = in.nextInt();
		int[][] f = new int[2 * n][n];
		for (int i = 0; i < n; i++) {
			f[0][i] = in.nextInt() - 1;
		}
		for (int i = 0; i < n; i++) {
			for (int j = 1; j < 2 * n; j++) {
				f[j][i] = f[0][f[j - 1][i]];
			}
		}
		BigInteger res = BigInteger.ONE;
		for (int i = 0; i < n; i++) {
			for (int pw = 0; pw < 2 * n; pw++) {
				if (f[pw][f[pw][i]] == f[pw][i]) {
				//	out.println(pw + 1);
					BigInteger g = BigInteger.valueOf(pw + 1).gcd(res);
					res = res.multiply(BigInteger.valueOf(pw + 1)).divide(g);
					break;
				}
			}
		}
		out.println(res);
	}

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

		solve();

		out.close();
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

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

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(in.br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

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

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

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

public class F {
	FastScanner in;
	PrintWriter out;

	void solve() {
		int n = in.nextInt();
		int[] f = new int[n];
		for (int i = 0; i < n; i++) {
			f[i] = in.nextInt() - 1;
		}
		BigInteger res = BigInteger.ONE;
		for (int i = 0; i < n; i++) {
			int[] d = new int[n];
			Arrays.fill(d, -1);
			int cur = i;
			int curd = 0;
			int d0 = -1, d1 = -1;
			while (true) {
				d[cur] = curd;
				curd++;
				cur = f[cur];
				if (d[cur] != -1) {
					d0 = d[cur];
					d1 = curd - d[cur];
					break;
				}
			}
			if (d0 == 0)
				d0 = 1;
			//System.out.println(d0 + " " + d1);
			long x = ((d0 + d1 - 1) / d1) * d1;
			//System.out.println(x);
			BigInteger g = BigInteger.valueOf(x).gcd(res);
			res = res.multiply(BigInteger.valueOf(x)).divide(g);
		}
		out.println(res);
	}

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

		solve();

		out.close();
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

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

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(in.br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

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

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

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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author unknown
 */
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();
	}
}

class TaskC {
    final int N = 207;

    int n;
    int[] a = new int[N];
    int[] dist = new int[N];

    BigInteger gcd(BigInteger a, BigInteger b) {
        if (a.compareTo(BigInteger.ZERO) == 0) return b;
        return gcd(b.mod(a), a);
    }

    BigInteger lcm(BigInteger a, BigInteger b) {
        return a.divide(gcd(a, b)).multiply(b);
    }

    public void solve(int testNumber, InputReader in, PrintWriter out) {
        n = in.nextInt();
        for (int i = 1; i <= n; ++i) a[i] = in.nextInt();
        int maxi = 0;
        BigInteger ans = BigInteger.ONE;
        for (int i = 1; i <= n; ++i) {
            for (int j = 0; j <= n; ++j) dist[j] = -1;
            dist[i] = 0;
            int j = i;
            int cd = 0;
            while (dist[a[j]] == -1) {
                dist[a[j]] = ++cd;
                j = a[j];
            }
            int len = cd - dist[a[j]] + 1;
            int pre = cd - len + 1;
            maxi = Math.max(maxi, pre);
            ans = lcm(ans, BigInteger.valueOf(len));
        }
        if (ans.compareTo(BigInteger.valueOf(maxi)) == -1) ans = BigInteger.valueOf(maxi);
        out.println(ans);
    }

}

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 javafx.geometry.Pos;
import javafx.util.Pair;

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.security.cert.PolicyNode;
import java.util.*;

public class Solution {
    BufferedReader in;
    PrintWriter out;
    StringTokenizer st;

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

    final int inf = Integer.MAX_VALUE / 2;
    final double eps = 0.0000000001;

    int rd() throws IOException {
        return Integer.parseInt(nextToken());
    }
    double rdd() throws IOException {
        return Double.parseDouble(nextToken());
    }
    long rdl() throws IOException {
        return Long.parseLong(nextToken());
    }

    int n;
    int[] a;

    int f(int x, int l){
        if (l <= 1){
            return a[x];
        } else {
            return a[f(x, l - 1)];
        }
    }

    void solve() throws IOException {
        n = rd();
        a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = rd() - 1;
        }
        for (int k = 1; k <= n + n; k++) {
            for (int i = 0; i < n; i++) {
                if (f(i, 2 * k) == f(i, k)) {
                    out.println(k);
                    out.flush();
                    System.exit(0);
                } else break;
            }
        }
    }

    void run() throws IOException {
        try {
//            in = new BufferedReader(new FileReader("notation.in"));
//            out = new PrintWriter("notation.out");
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
            Locale.setDefault(Locale.UK);
            solve();
        } catch (Exception e) {
            e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
        } finally {
            out.close();
        }
    }

    public static void main(String Args[]) throws IOException {
        new Solution().run();
    }
}

import javafx.geometry.Pos;
import javafx.util.Pair;

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.security.cert.PolicyNode;
import java.util.*;

public class Solution {
    BufferedReader in;
    PrintWriter out;
    StringTokenizer st;

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

    final int inf = Integer.MAX_VALUE / 2;
    final double eps = 0.0000000001;

    int rd() throws IOException {
        return Integer.parseInt(nextToken());
    }
    double rdd() throws IOException {
        return Double.parseDouble(nextToken());
    }
    long rdl() throws IOException {
        return Long.parseLong(nextToken());
    }

    int n;
    int[] a;

    int[] f(int[] x, int[] a){
        int[] r = new int[n];
        for (int i = 0; i < n; i++) r[i] = a[x[i]];
        return r;
    }

    boolean neq(int[] a, int[] b) {
        for (int i = 0; i < n; i++)
            if (a[i] != b[i]) return true;
        return false;
    }

    void solve() throws IOException {
        n = rd();
        a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = rd() - 1;
        }
        BigInteger ans = BigInteger.ONE;
        long ppmax = 0;
        int[] b = new int[n];
        for (int i = 0; i < n; i++) {
            if (b[i] == 0) {
                int j1 = i;
                for (int j = 0; j < 300; j++) j1 = a[j1];
                int j2 = a[j1];
                int cnt = 1;
                while (j1 != j2) {
                    cnt++;
                    j1 = a[j1];
                    j2 = a[a[j2]];
                }
                ans = ans.multiply(BigInteger.valueOf(cnt)).divide(ans.gcd(BigInteger.valueOf(cnt)));
                j1 = i;
                j2 = i;
                for (int j = 0; j < cnt; j++) j2 = a[j2];
                int pp = 0;
                while (j1 != j2) {
                    pp++;
                    j1 = a[j1];
                    j2 = a[j2];
                }
                ppmax = Math.max(ppmax, pp);
                j1 = i;
                for (int j = 0; j < 300; j++) { b[j1] = 1; j1 = a[j1]; }
            }
        }
        out.println(ans.add(BigInteger.valueOf(Math.max(ppmax - 1, 0))));
    }

    void run() throws IOException {
        try {
//            in = new BufferedReader(new FileReader("notation.in"));
//            out = new PrintWriter("notation.out");
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
            Locale.setDefault(Locale.UK);
            solve();
        } catch (Exception e) {
            e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
        } finally {
            out.close();
        }
    }

    public static void main(String Args[]) throws IOException {
        new Solution().run();
    }
}

import javafx.geometry.Pos;
import javafx.util.Pair;

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.security.cert.PolicyNode;
import java.util.*;

public class Solution {
    BufferedReader in;
    PrintWriter out;
    StringTokenizer st;

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

    final int inf = Integer.MAX_VALUE / 2;
    final double eps = 0.0000000001;

    int rd() throws IOException {
        return Integer.parseInt(nextToken());
    }
    double rdd() throws IOException {
        return Double.parseDouble(nextToken());
    }
    long rdl() throws IOException {
        return Long.parseLong(nextToken());
    }

    int n;
    int[] a;

    int[] f(int[] x, int[] a){
        int[] r = new int[n];
        for (int i = 0; i < n; i++) r[i] = a[x[i]];
        return r;
    }

    boolean neq(int[] a, int[] b) {
        for (int i = 0; i < n; i++)
            if (a[i] != b[i]) return true;
        return false;
    }

    void solve() throws IOException {
        n = rd();
        a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = rd() - 1;
        }
        BigInteger ans = BigInteger.ONE;
        long ppmax = 0;
        for (int i = 0; i < n; i++) {
                int j1 = i;
                for (int j = 0; j < 300; j++) j1 = a[j1];
                int j2 = a[j1];
                int cnt = 1;
                while (j1 != j2) {
                    cnt++;
                    j1 = a[j1];
                    j2 = a[a[j2]];
                }
                ans = ans.multiply(BigInteger.valueOf(cnt)).divide(ans.gcd(BigInteger.valueOf(cnt)));
                j1 = i;
                j2 = i;
                for (int j = 0; j < cnt; j++) j2 = a[j2];
                int pp = 0;
                while (j1 != j2) {
                    pp++;
                    j1 = a[j1];
                    j2 = a[j2];
                }
                ppmax = Math.max(ppmax, pp);
                j1 = i;
        }
        out.println(ans.add(BigInteger.valueOf(Math.max(ppmax - 1, 0))));
    }

    void run() throws IOException {
        try {
//            in = new BufferedReader(new FileReader("notation.in"));
//            out = new PrintWriter("notation.out");
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
            Locale.setDefault(Locale.UK);
            solve();
        } catch (Exception e) {
            e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
        } finally {
            out.close();
        }
    }

    public static void main(String Args[]) throws IOException {
        new Solution().run();
    }
}

import javafx.geometry.Pos;
import javafx.util.Pair;

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.security.cert.PolicyNode;
import java.util.*;

public class Solution {
    BufferedReader in;
    PrintWriter out;
    StringTokenizer st;

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

    final int inf = Integer.MAX_VALUE / 2;
    final double eps = 0.0000000001;

    int rd() throws IOException {
        return Integer.parseInt(nextToken());
    }
    double rdd() throws IOException {
        return Double.parseDouble(nextToken());
    }
    long rdl() throws IOException {
        return Long.parseLong(nextToken());
    }

    int n;
    int[] a;

    int f(int x, int l){
        if (l <= 1){
            return a[x];
        } else {
            return a[f(x, l - 1)];
        }
    }

    void solve() throws IOException {
        n = rd();
        a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = rd() - 1;
        }
        for (int k = 1; k <= n + 2; k++) {
            int cnt = 0;
            for (int i = 0; i < n; i++) {
                if (f(i, 2 * k) == f(i, k)) {
                    cnt++;
                }
            }
            if (cnt == n) {
                out.println(k);
                out.flush();
                System.exit(0);
            }
        }
    }

    void run() throws IOException {
        try {
//            in = new BufferedReader(new FileReader("notation.in"));
//            out = new PrintWriter("notation.out");
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
            Locale.setDefault(Locale.UK);
            solve();
        } catch (Exception e) {
            e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
        } finally {
            out.close();
        }
    }

    public static void main(String Args[]) throws IOException {
        new Solution().run();
    }
}

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

@SuppressWarnings("unchecked")

public class Main implements Runnable {

    public static final String FILENAME = null;

    final int maxn = 210;
    int p[] = new int[maxn];
    int mark[] = new int[maxn];

    private void solve() throws IOException {
        int n = nextInt();
        for (int i = 0; i < n; ++i) p[i] = nextInt() - 1;
        int min = 1;
        BigInteger del = BigInteger.ONE;
        for (int i = 0; i < n; ++i) if (mark[i] == 0)
        {
            int x = i;
            int cnt = 0;
            while (true)
            {
                mark[x] = ++cnt;
                if (mark[p[x]] == 0)
                {
                    x = p[x];
                }
                else if (mark[p[x]] > 0)
                {
                    min = Math.max(min, mark[p[x]] - 1);
                    BigInteger cyc = BigInteger.valueOf(mark[x] - mark[p[x]] + 1);
                    del = del.multiply(cyc).divide(del.gcd(cyc));
                    break;
                }
                else break;
            }
            x = i;
            while (true)
            {
                mark[x] = -1;
                if (mark[p[x]] != -1) x = p[x];
                else break;
            }
        }
        BigInteger res = del;
        while (res.compareTo(BigInteger.valueOf(min)) < 0) res = res.add(del);
        out.println(res);

    }
    // -----------------------------------------------
    private BufferedReader br;
    private StringTokenizer _st;
    private PrintWriter out;

    private void myAssert(boolean assertion) {
        if (!assertion) throw new AssertionError();
    }
    private void dbg(Object...os){
        System.err.println(Arrays.deepToString(os));
        System.err.flush();
    }
    private String next() throws IOException {
        while (_st == null || !_st.hasMoreTokens()) {
            String s = br.readLine();
            if (s == null) return null;
            _st = new StringTokenizer(s);
        }
        return _st.nextToken();
    }
    private int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
    private long nextLong() throws IOException {
        return Long.parseLong(next());
    }
    private double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
    private String nextLine() throws IOException {
        _st = null;
        return br.readLine();
    }
    public void run() {
        long startTime = System.nanoTime();
        try {
            if (FILENAME == null) {
                br = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                br = new BufferedReader(new FileReader(FILENAME + ".in"));
                out = new PrintWriter(FILENAME + ".out");
            }
            try {
                solve();
            } finally {
                out.close();
            }
        } catch (IOException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
        }
        long finishTime = System.nanoTime();
//      System.err.printf("Time = %.3f\n", (finishTime - startTime) / 1e9);
    }
    public static void main(String[] args) {
        new Thread(new Main()).start();
    }

}

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

@SuppressWarnings("unchecked")

public class Main implements Runnable {

    public static final String FILENAME = null;

    final int maxn = 210;
    int p[] = new int[maxn];
    int mark[] = new int[maxn];

    private void solve() throws IOException {
        int n = nextInt();
        for (int i = 0; i < n; ++i) p[i] = nextInt() - 1;
        int min = 1;
        BigInteger del = BigInteger.ONE;
        for (int i = 0; i < n; ++i) if (mark[i] == 0)
        {
            int x = i;
            int cnt = 0;
            int cc = 0;
            while (true)
            {
                mark[x] = ++cnt;
                if (mark[p[x]] == 0)
                {
                    x = p[x];
                }
                else if (mark[p[x]] > 0)
                {
                    min = Math.max(min, mark[p[x]] - 1);
                    BigInteger cyc = BigInteger.valueOf(mark[x] - mark[p[x]] + 1);
                    del = del.multiply(cyc).divide(del.gcd(cyc));
                    cc = mark[p[x]];
                    break;
                }
                else
                {
                    min = Math.max(min, mark[x] - 1 - mark[p[x]]);
                    break;
                }

            }
            x = i;
            cnt = 0;
            while (true)
            {
                mark[x] = Math.min(-1, (++cnt) - cc - 1);
                if (mark[p[x]] != -1) x = p[x];
                else break;
            }
        }
        BigInteger res = del;
        while (res.compareTo(BigInteger.valueOf(min)) < 0) res = res.add(del);
        out.println(res);

    }
    // -----------------------------------------------
    private BufferedReader br;
    private StringTokenizer _st;
    private PrintWriter out;

    private void myAssert(boolean assertion) {
        if (!assertion) throw new AssertionError();
    }
    private void dbg(Object...os){
        System.err.println(Arrays.deepToString(os));
        System.err.flush();
    }
    private String next() throws IOException {
        while (_st == null || !_st.hasMoreTokens()) {
            String s = br.readLine();
            if (s == null) return null;
            _st = new StringTokenizer(s);
        }
        return _st.nextToken();
    }
    private int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
    private long nextLong() throws IOException {
        return Long.parseLong(next());
    }
    private double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
    private String nextLine() throws IOException {
        _st = null;
        return br.readLine();
    }
    public void run() {
        long startTime = System.nanoTime();
        try {
            if (FILENAME == null) {
                br = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                br = new BufferedReader(new FileReader(FILENAME + ".in"));
                out = new PrintWriter(FILENAME + ".out");
            }
            try {
                solve();
            } finally {
                out.close();
            }
        } catch (IOException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
        }
        long finishTime = System.nanoTime();
//      System.err.printf("Time = %.3f\n", (finishTime - startTime) / 1e9);
    }
    public static void main(String[] args) {
        new Thread(new Main()).start();
    }

}

//import java.awt.Dimension;
import java.awt.Point;
import java.io.*;
import static java.lang.Math.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import java.util.*;
import static java.util.Arrays.*;
//import java.math.BigInteger;
//import static java.lang.Character.*;
//import static java.lang.Math.*;
//import static java.math.BigInteger.*;

//import static java.util.Arrays.*;

//import java.awt.Point; // interger !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//import java.awt.Polygon;
//import java.awt.Rectangle;
//import java.awt.geom.AffineTransform;
//import java.awt.geom.Line2D;
//import java.awt.geom.Point2D;
//import javafx.scene.shape.Line;
//import javafx.scene.transform.Rotate;

//<editor-fold defaultstate="collapsed" desc="Main">
public class Main implements Runnable{

    // https://netbeans.org/kb/73/java/editor-codereference_ru.html#display

    static boolean oj;

    @Override
    public void run(){
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception e) {
        }
        oj = true;
        try {
            oj = System.getProperty("MYLOCAL") == null;
        } catch (Exception e) {
        }
//
        if (oj) {
            sc = new FastScanner(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
        } else {
            try {
                sc = new FastScanner(new FileReader("input.txt"));
                out = new PrintWriter(new FileWriter("output.txt"));
            } catch (IOException e) {
                MLE();
            }
        }
        Solver s = new Solver();
        s.sc = sc;
        s.out = out;

        s.solve();
        if (!oj) {
            err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
            err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        }
        out.flush();
    }

    private void show(int[] arr) {
        for (int v : arr) {
            err.print(" " + v);
        }
        err.println();
    }

    public static void exit() {
        err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
        err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
        out.flush();
        out.close();
        System.exit(0);
    }

    public static void MLE() {
        int[][] arr = new int[1024 * 1024][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[1024 * 1024];
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        //new Main().run();
        new Thread(null, new Main(), "myThread", 100 * 1024 * 1024).start();
    }

    static long timeBegin = System.currentTimeMillis();
    static FastScanner sc;
    static PrintWriter out;
    static PrintStream err = System.err;
}
    //</editor-fold>

//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {

    BufferedReader br;
    StringTokenizer st;

    FastScanner(InputStreamReader reader) {
        br = new BufferedReader(reader);
        st = new StringTokenizer("");
    }

    String next() {
        while (!st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (Exception ex) {
                return null;
            }
        }
        return st.nextToken();
    }

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

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

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

    String nextLine() {
        try {
            return br.readLine();
        } catch (IOException ex) {
            return null;
        }
    }
}
//</editor-fold>

class Solver {

    void aser(boolean OK) {
        if (!OK) {
            Main.MLE();
        }
    }

    FastScanner sc;
    PrintWriter out;
    static PrintStream err = System.err;

//    int n;
//    int[] f, fOrg;
//
//    void solve(){
//        n = sc.nextInt();
//        f = new int[n + 1];
//        for (int x = 1; x <= n; x++)
//            f[x] = sc.nextInt();
//        fOrg = f.clone();
//
//        for( int iter = 1; iter <= 14; ++iter ){
//            err.printf("iter: %5d", iter); err.print("    ");
//            for(int i = 1;i <= n; ++i) err.print(" " + f[i]);
//            if( cheack() ){
//                err.print("\t OK!");
//                //break;
//            }
//            err.println();
//
//            //
//            int[] fNext = new int[n + 1];
//            for (int x = 1; x <= n; x++) {
//                fNext[x] = fOrg[f[x]];
//            }
//            f = fNext;
//        }
//    }
//
//    private boolean cheack() {
//        for (int x = 1; x <= n; x++) {
//            if( f[f[x]] != f[x] ){
//                return false;
//            }
//        }
//        return true;
//    }

    int n;
    int[] f;

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

    long getCyc(final int start){
        int[] timeIn = new int[n + 1];
        fill( timeIn, -1 );
        for( int v = start, timer = 0; ; v = f[v], ++timer ){
            if (timeIn[v] != -1) {
                if( start == v )
                    return timer;
                else
                    return -timeIn[v];
            }
            timeIn[v] = timer;
        }
    }

    void solve(){
        n = sc.nextInt();
        f = new int[n + 1];
        for (int x = 1; x <= n; x++)
            f[x] = sc.nextInt();
        long maxDist = 0;
        long lcm = 0;
        for (int start = 1; start <= n; start++) {
            long c = getCyc(start);
            if( c < 0 ) maxDist = max( maxDist, -c );
            else {
                if( lcm == 0 ) lcm = c;
                else lcm = lcm / gcd(lcm,c) * c;
            }
            err.printf("%d %d\n", start, c);
        }
        lcm *= (maxDist + lcm - 1) / lcm;
        out.println(lcm);
    }

}

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Main {

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

        InputReader sc = new InputReader(new BufferedInputStream(System.in));
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(System.out)));

        int size = sc.nextInt();
        ArrayList<Integer> stringGraph = new ArrayList<Integer>();
        for (int i = 0; i < size; i++) {
            stringGraph.add(sc.nextInt());
        }
        Graph g = new Graph(size, stringGraph);
        out.print(g.findIdempotent());

        out.flush();
        out.close();

    }

    public static int lcm(int m, int n) {

        // prompts user for values to find the LCM for, then saves them to m and
        // n
        int lcm = (n == m || n == 1) ? m : (m == 1 ? n : 0);
        /*
         * this section increases the value of mm until it is greater / than or
         * equal to nn, then does it again when the lesser / becomes the
         * greater--if they aren't equal. If either value is 1, / no need to
         * calculate
         */
        if (lcm == 0) {
            int mm = m, nn = n;
            while (mm != nn) {
                while (mm < nn) {
                    mm += m;
                }
                while (nn < mm) {
                    nn += n;
                }
            }
            lcm = mm;
        }
        return lcm;
    }

}

class InputReader {
    BufferedReader reader;
    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 long nextLong() {
        return Long.parseLong(next());
    }

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

class GraphNode {

    private boolean visited;
    private int content;
    private ArrayList<Edge> edges;

    public int getContent() {
        return content;
    }

    public ArrayList<Edge> getInComes() {
        return (ArrayList<Edge>) edges.subList(1, edges.size() - 1);
    }

    public void addEdgeToInComes(Edge add) {
        this.edges.add(add);
    }

    public Edge getOutGoing() {
        return edges.get(0);
    }

    public void addOutGoingEdge(Edge add) {
        this.edges.add(0, add);
    }

    public GraphNode(int content) {
        this.content = content;
        this.edges = new ArrayList<Edge>();
        this.visited = false;
    }

    public int getInDegree() {
        return edges.subList(1, edges.size()).size();
    }

    public boolean isVisited() {
        return visited;
    }

    public void setVisited(boolean visited) {
        this.visited = visited;
    }

    public ArrayList<Edge> getEdges() {
        return this.edges;
    }
}

class Graph {
    private ArrayList<GraphNode> nodes;

    public Graph(int size, ArrayList<Integer> edges) {
        nodes = new ArrayList<GraphNode>();
        for (int i = 1; i <= size; i++) {
            nodes.add(new GraphNode(i));
        }
        for (int i = 0; i < edges.size(); i++) {
            addEdge(i + 1, edges.get(i));
        }
    }

    public void addEdge(int from, int to) {
        new Edge(nodes.get(from - 1), nodes.get(to - 1));
    }

    public int depthFirstSearch(BinaryTree<Integer> visitTree,
            ArrayList<GraphNode> startNodes, BinaryTree<Integer> cycleNodes,
            GraphNode current) {
        int k = -1;
        current.setVisited(true);
        visitTree.delete(current.getContent());

        if (current.getInDegree() == 0) {
            startNodes.add(current);
        }

        for (int i = 0; i < current.getEdges().size(); i++) {
            if (!current.getEdges().get(i).isVisited()) {
                GraphNode adjacent;
                if (i == 0)
                    adjacent = current.getEdges().get(i).getTo();
                else
                    adjacent = current.getEdges().get(i).getFrom();
                current.getEdges().get(i).setVisited(true);
                if (!adjacent.isVisited()) {
                    int m = depthFirstSearch(visitTree, startNodes, cycleNodes,
                            adjacent);
                    if (m > 0) {
                        k = m;
                    }
                } else {
                    k = adjacent.getContent();
                }
            }
        }

        if (k != -1) {
            cycleNodes.add(current.getContent());
        }
        if (k == current.getContent()) {
            k = -1;
        }
        return k;
    }

    public int findIdempotent() {
        ArrayList<Integer> visit = new ArrayList<Integer>();
        for (int i = 1; i <= this.nodes.size(); i++) {
            visit.add(i);
        }
        int distanceToCycle = 1;
        ArrayList<Integer> sizeOfCyles = new ArrayList<Integer>();
        BinaryTree<Integer> visitTree = new BinaryTree<Integer>(
                Integer.MAX_VALUE, visit);
        while (visitTree.size() > 0) {
            BinaryTree<Integer> cycleNodes = new BinaryTree<Integer>(
                    Integer.MAX_VALUE);
            ArrayList<GraphNode> startNodes = new ArrayList<GraphNode>();
            depthFirstSearch(visitTree, startNodes, cycleNodes,
                    this.nodes.get(visitTree.peek() - 1));
            sizeOfCyles.add(cycleNodes.size());
            while (!startNodes.isEmpty()) {
                int distance = 1;
                GraphNode mover = startNodes.remove(startNodes.size() - 1);
                while (true) {
                    if (cycleNodes.contains(mover.getOutGoing().getTo()
                            .getContent())) {
                        break;
                    }
                    distance++;
                    mover = mover.getOutGoing().getTo();
                }
                if (distance > distanceToCycle) {
                    distanceToCycle = distance;
                }
            }
        }
        int lcm = sizeOfCyles.remove(sizeOfCyles.size() - 1);
        while (sizeOfCyles.size() > 0) {
            lcm = Main.lcm(lcm, sizeOfCyles.remove(sizeOfCyles.size() - 1));
        }
        return (int) (Math.ceil((double) distanceToCycle / lcm)) * lcm;
    }
}

class BinaryTree<T extends Comparable<T>> {
    private Node<T> header;
    private int numberOfElements;

    public BinaryTree(T header) {
        this.header = new Node<T>(header);
        numberOfElements = 0;
    }

    public BinaryTree(T header, ArrayList<T> list) {
        this(header);
        this.header.setLeftChild(sortedListToTree(0, list.size() - 1, list));
    }

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

    public Node<T> getHeader() {
        return this.header;
    }

    public void print(Node<T> a) {
        if (a != null) {
            print(a.getLeftChild());
            System.out.println(a.getContent());
            print(a.getRightChild());
        }
    }

    private Node<T> sortedListToTree(int left, int right, ArrayList<T> list) {
        Node<T> ret = null;
        if (left <= right) {
            int middle = (left + right) / 2;
            ret = new Node<T>(list.get(middle));
            ret.setLeftChild(sortedListToTree(left, middle - 1, list));
            ret.setRightChild(sortedListToTree(middle + 1, right, list));
        }
        this.numberOfElements = list.size();
        return ret;
    }

    public void add(T add) {
        Node<T> rear = null;
        Node<T> front = this.header;
        boolean leftOrRight = true;
        while (front != null) {
            if (add.compareTo(front.getContent()) > 0) {
                rear = front;
                front = front.getRightChild();
                leftOrRight = false;
            } else if (add.compareTo(front.getContent()) < 0) {
                rear = front;
                front = front.getLeftChild();
                leftOrRight = true;
            } else {
                break;
            }
        }
        if (leftOrRight) {
            rear.setLeftChild(new Node<T>(add));
        } else {
            rear.setRightChild(new Node<T>(add));
        }
        this.numberOfElements++;
    }

    public boolean contains(T search) {
        if (find(search) != null) {
            return true;
        } else {
            return false;
        }
    }

    public Node<T> find(T key) {
        Node<T> found = null, mover = this.header;
        while (mover != null) {
            if (key.compareTo(mover.getContent()) > 0) {
                mover = mover.getRightChild();
            } else if (key.compareTo(mover.getContent()) < 0) {
                mover = mover.getLeftChild();
            } else {
                found = mover;
                break;
            }
        }
        return found;
    }

    public void delete(T deleteNum) {
        Node<T> mover = this.header;
        Node<T> backMover = null;
        while (mover != null) {
            if (deleteNum.equals(mover.getContent())) {
                break;
            } else if (deleteNum.compareTo(mover.getContent()) == -1) {
                backMover = mover;
                mover = mover.getLeftChild();
            } else {
                backMover = mover;
                mover = mover.getRightChild();
            }
        }

        Node<T> replace = null;
        Node<T> backReplace = null;

        if (mover.getLeftChild() != null) {
            replace = mover.getLeftChild();
            while (replace.getRightChild() != null) {
                backReplace = replace;
                replace = replace.getRightChild();
            }
            if (backReplace != null) {
                backReplace.setRightChild(replace.getLeftChild());
                replace.setLeftChild(mover.getLeftChild());
            }
            replace.setRightChild(mover.getRightChild());
        } else if (mover.getRightChild() != null) {
            replace = mover.getRightChild();
            while (replace.getLeftChild() != null) {
                backReplace = replace;
                replace = replace.getLeftChild();
            }
            if (backReplace != null) {
                backReplace.setLeftChild(replace.getRightChild());
                replace.setRightChild(mover.getRightChild());
            }
            replace.setLeftChild(mover.getLeftChild());
        }

        if (mover.getContent().compareTo(backMover.getContent()) == -1) {
            backMover.setLeftChild(replace);
        } else {
            backMover.setRightChild(replace);
        }
        this.numberOfElements--;
    }

    public T pop() {
        T temp = this.header.getLeftChild().getContent();
        delete(temp);
        return temp;
    }

    public T peek() {
        return this.header.getLeftChild().getContent();
    }
}

class Edge {
    private GraphNode from;
    private GraphNode to;
    private boolean visited;

    public Edge(GraphNode from, GraphNode to) {
        this.from = from;
        this.to = to;
        this.visited = false;
        from.addOutGoingEdge(this);
        to.addEdgeToInComes(this);
    }

    public GraphNode getFrom() {
        return from;
    }

    public void setFrom(GraphNode from) {
        this.from = from;
    }

    public GraphNode getTo() {
        return to;
    }

    public void setTo(GraphNode to) {
        this.to = to;
    }

    public boolean isVisited() {
        return visited;
    }

    public void setVisited(boolean visited) {
        this.visited = visited;
    }

}

class Node<T> {
    private T content;
    private Node<T> rightChild;
    private Node<T> leftChild;

    public Node<T> getRightChild() {
        return rightChild;
    }

    public void setRightChild(Node<T> rightChild) {
        this.rightChild = rightChild;
    }

    public Node<T> getLeftChild() {
        return leftChild;
    }

    public void setLeftChild(Node<T> leftChild) {
        this.leftChild = leftChild;
    }

    public Node(T content) {
        super();
        this.content = content;
    }

    public T getContent() {
        return content;
    }

    public void setContent(T content) {
        this.content = content;
    }

}

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

public class C
{
	int[] f;
	int N;

	void solve()
	{
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		f = new int[N];
		for (int i = 0; i < N; i++)
			f[i] = sc.nextInt() - 1;
		TreeSet<Integer> constraints = new TreeSet<Integer>();
		int minVal = 0;
		for (int i = 0; i < N; i++)
		{
			int[] dist = new int[N];
			Arrays.fill(dist, -1);
			int cnt = 0;
			int v = i;
			while (true)
			{
				if (dist[v] >= 0)
				{
					minVal = Math.max(minVal, dist[v]);
					constraints.add(cnt - dist[v]);
					break;
				}
				dist[v] = cnt++;
				v = f[v];
			}
		}
		BigInteger lo = BigInteger.valueOf(minVal);
		BigInteger ans = BigInteger.ONE;
		for (int x : constraints)
		{
			if (x % 2 == 0)
				x /= 2;
			BigInteger o = BigInteger.valueOf(x);
			ans = ans.multiply(o).divide(ans.gcd(o));
		}
		BigInteger fans = ans;
		while (fans.compareTo(lo) < 0)
			fans = fans.add(ans);
		System.out.println(fans);
	}

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

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

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Andrey Rechitsky (arechitsky@gmail.com)
 */
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);
		TaskC solver = new TaskC();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskC {
    int MAX = 10000;
    public void solve(int testNumber, FastScanner in, FastPrinter out) {
        int n = in.nextInt();
        int [][]f = new int[MAX][n];
        for (int i = 0; i < n; i++) {
            f[0][i] = in.nextInt()-1;
        }
        for (int i = 1; i < MAX; i++) {
            for (int j = 0; j < n; j++) {
                f[i][j] = f[0][f[i-1][j]];
            }
        }
        int ans = -1;
        for (int i = 0; i < MAX; i++) {
            boolean hasAns = true;
            for (int j = 0; j < n; j++) {
                if (f[i][j]!=f[i][f[i][j]]) hasAns = false;
            }
            if (hasAns){
                ans = i;
                break;
            }
        }
        //if (ans==-1) throw new RuntimeException();
        out.printLine(ans+1);
    }
}

class FastScanner {

    private BufferedReader reader;
    private StringTokenizer st;

    public FastScanner(InputStream stream) {
        this.reader = new BufferedReader(new InputStreamReader(stream));
        this.st = new StringTokenizer("");
    }

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

    public String next(){
        while (!st.hasMoreTokens()){
            st = new StringTokenizer(readLine());
        }
        return st.nextToken();
    }

    private String readLine() {
        try {
            String line = reader.readLine();
            if (line==null) throw new InputMismatchException();
            return line;
        } catch (IOException e) {
            throw new InputMismatchException();
        }
    }

}

class FastPrinter {
    private final PrintWriter writer;

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

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

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

}

//package codeforce;
import java.io.*;
import java.util.*;
public class idempotentcomponents {
public static void main(String[] args) throws Exception
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw=new PrintWriter(System.out);
    int n=Integer.parseInt(br.readLine());
    StringTokenizer st=new StringTokenizer(br.readLine());
    int[] a=new int[n];
    for(int i=0;i<n;i++)
    {

    a[i]=Integer.parseInt(st.nextToken())-1;

    }
    long min=1;
    long z=1;
    for(int i=0;i<n;i++)
    {

        HashMap<Integer,Integer> hs=new HashMap();
        hs.put(i,0);
        int next=a[i];

        int k=1;
        while(!hs.containsKey(next))
        {
            hs.put(next, k);
            k++;
            next=a[next];
        }
        if(next==i)
        {
            z=lcm(z,k);
        }
        else
        {
            if((k=hs.get(next))>min)
            {
                min=k;
            }
        }
    }

    if(min%z==0)
    {
        System.out.println(min);
    }
    else
    {
        System.out.println((z/min+1)*z);
    }
    }

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

//package codeforce;
import java.io.*;
import java.util.*;
public class idempotentcomponents {
public static void main(String[] args) throws Exception
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw=new PrintWriter(System.out);
    int n=Integer.parseInt(br.readLine());
    StringTokenizer st=new StringTokenizer(br.readLine());
    int[] a=new int[n];
    for(int i=0;i<n;i++)
    {

    a[i]=Integer.parseInt(st.nextToken())-1;

    }
    long min=1;
    long z=1;
    for(int i=0;i<n;i++)
    {

        HashMap<Integer,Integer> hs=new HashMap();
        hs.put(i,0);
        int next=a[i];

        int k=1;
        while(!hs.containsKey(next))
        {
            hs.put(next, k);
            k++;
            next=a[next];
        }
        System.out.println(next+" "+k);
        if(next==i)
        {
            z=lcm(z,k);
        }
        else
        {
            if((k=hs.get(next))>min)
            {
                min=k;
            }
        }
        //System.out.println("min is"+min+" z is   "+z);

    }
    //System.out.println(min%z == 0? min:(min/z+1)*z);
if(min%z==0)
    {
        System.out.println(min);
    }
    else
    {
        System.out.println((min/z+1)*z);
    }
    }

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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * #
 * @author pttrung
 */
public class C_VK2015_Round3 {
	public static int[][]dp;
    public static long MOD = 1000000007;

    public static void main(String[] args) throws FileNotFoundException {
        // PrintWriter out = new PrintWriter(new FileOutputStream(new File(
        // "output.txt")));
        PrintWriter out = new PrintWriter(System.out);
        Scanner in = new Scanner();
        int n = in.nextInt();
        dp = new int[n + 1][n + 1];
        for(int[]a : dp){
        	Arrays.fill(a,-1);
        }
        int[]data = new int[n + 1];
        for(int i = 0; i < n; i++){
        	data[i + 1] = in.nextInt();
        }
        long result = 1;
        for(int i = 1; i <= n; i++){
        	long v = 0;
        	for(int j = 1; j <= n; j++){
        		int a = cal(i, j, data);
        		int b = cal(a, j, data);
        		if(a == b){
        			v = j;
        			break;
        		}
        	}

        	result = result*v/gcd(v,result);
        }
        out.println(result);
        out.close();
    }

    public static int cal(int index, int x ,int[]data){
    	if(x == 0){
    		return index;
    	}
    	if(dp[index][x] != -1){
    		return dp[index][x];
    	}
    	return dp[index][x] = cal(data[index], x - 1, data);
    }

    public static int[] KMP(String val) {
        int i = 0;
        int j = -1;
        int[] result = new int[val.length() + 1];
        result[0] = -1;
        while (i < val.length()) {
            while (j >= 0 && val.charAt(j) != val.charAt(i)) {
                j = result[j];
            }
            j++;
            i++;
            result[i] = j;
        }
        return result;

    }

    public static boolean nextPer(int[] data) {
        int i = data.length - 1;
        while (i > 0 && data[i] < data[i - 1]) {
            i--;
        }
        if (i == 0) {
            return false;
        }
        int j = data.length - 1;
        while (data[j] < data[i - 1]) {
            j--;
        }
        int temp = data[i - 1];
        data[i - 1] = data[j];
        data[j] = temp;
        Arrays.sort(data, i, data.length);
        return true;
    }

    public static int digit(long n) {
        int result = 0;
        while (n > 0) {
            n /= 10;
            result++;
        }
        return result;
    }

    public static double dist(long a, long b, long x, long y) {
        double val = (b - a) * (b - a) + (x - y) * (x - y);
        val = Math.sqrt(val);
        double other = x * x + a * a;
        other = Math.sqrt(other);
        return val + other;

    }

    public static class Point implements Comparable<Point> {

        int x, y;

        public Point(int start, int end) {
            this.x = start;
            this.y = end;
        }

        @Override
        public int hashCode() {
            int hash = 5;
            hash = 47 * hash + this.x;
            hash = 47 * hash + this.y;
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Point other = (Point) obj;
            if (this.x != other.x) {
                return false;
            }
            if (this.y != other.y) {
                return false;
            }
            return true;
        }

        @Override
        public int compareTo(Point o) {
            return x - o.x;
        }
    }

    public static class FT {

        long[] data;

        FT(int n) {
            data = new long[n];
        }

        public void update(int index, long value) {
            while (index < data.length) {
                data[index] += value;
                index += (index & (-index));
            }
        }

        public long get(int index) {
            long result = 0;
            while (index > 0) {
                result += data[index];
                index -= (index & (-index));
            }
            return result;

        }
    }

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

    public static long pow(long a, long b) {
        if (b == 0) {
            return 1;
        }
        if (b == 1) {
            return a;
        }
        long val = pow(a, b / 2);
        if (b % 2 == 0) {
            return val * val % MOD;
        } else {
            return val * (val * a % MOD) % MOD;

        }
    }

    static class Scanner {

        BufferedReader br;
        StringTokenizer st;

        public Scanner() throws FileNotFoundException {
            // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
            br = new BufferedReader(new InputStreamReader(System.in));
            //  br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
        }

        public String next() {

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

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

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

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

        public String nextLine() {
            st = null;
            try {
                return br.readLine();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }

        public boolean endLine() {
            try {
                String next = br.readLine();
                while (next != null && next.trim().isEmpty()) {
                    next = br.readLine();
                }
                if (next == null) {
                    return true;
                }
                st = new StringTokenizer(next);
                return st.hasMoreTokens();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main {
	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;

		// InputStream inputStream = new FileInputStream("input.txt");
		// OutputStream outputStream = new FileOutputStream("output.txt");

		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);

		TaskA solver = new TaskA();

		solver.solve(in, out);

		out.close();
	}
}

class TaskA {

	public void solve(InputReader in, OutputWriter out) {

		int n = in.nextInt();
		int[] f = in.nextIntArray(n);

		int[] len = new int[n];
		int[] start = new int[n];
		int[] u = new int[n];
		for(int i=0; i<n; i++){
			Arrays.fill(u, 0);
			int cur = f[i], step=1;
			while(u[cur-1]==0){
				u[cur-1]=step++;
				cur = f[cur-1];
			}
			len[i] = step-u[cur-1];
			start[i] = u[cur-1];
		}

		/*
		for(int i=0; i<n; i++){
			System.out.print(len[i]+"("+start[i]+") ");
		}
		*/

		int a=1;
		for(int i=0; i<n; i++)
			if(start[i]==1) a = lcm(a,len[i]);
		int b = 0;
		for(int i=0; i<n; i++)
			b = Math.max(b,start[i]-1);

		//System.out.println(a+" "+b);
		out.write(a*((b+a-1)/a+1));
	}

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

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

}

class InputReader {

	BufferedReader reader;
	StringTokenizer tokenizer;

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

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

		return tokenizer.nextToken();
	}

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

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

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

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

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

		return res;
	}

}

class OutputWriter {

	PrintWriter out;

	public OutputWriter(OutputStream stream) {
		out = new PrintWriter(
				new BufferedWriter(new OutputStreamWriter(stream)));
	}

	public void write(Object... o) {
		for (Object cur : o)
			out.print(cur);
	}

	public void writeln(Object... o) {
		write(o);
		out.println();
	}

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

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

}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main {
	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;

		// InputStream inputStream = new FileInputStream("input.txt");
		// OutputStream outputStream = new FileOutputStream("output.txt");

		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);

		TaskA solver = new TaskA();

		solver.solve(in, out);

		out.close();
	}
}

class TaskA {

	public void solve(InputReader in, OutputWriter out) {

		int n = in.nextInt();
		int[] f = in.nextIntArray(n);

		/*
		int n = 100;
		int[] f = new int[100];
		Random r = new Random();
		for(int i=0; i<n; i++)
			f[i] = r.nextInt(n-1+1)+1;
		*/

		ArrayList<Integer>[] a = new ArrayList[n];
		int[] len = new int[n];
		int[] start = new int[n];
		int[] u;

		for(int i=0; i<n; i++){
			a[i] = new ArrayList<Integer>();
			u = new int[n+1];
			int cur = f[i],step=1;
			while(u[cur]==0){
				a[i].add(cur);
				u[cur]=step++;
				cur = f[cur-1];
			}
			len[i] = step-u[cur];
			start[i] = u[cur];
		}

		int left=1,right=100;
		int[] temp = new int[n];
		for(int t=1; ; t++){
			for(int i=0; i<n; i++){
				if(t>a[i].size()){
					temp[i] = a[i].get(start[i]+(t-start[i]+1)%len[i]-1);
				}else{
					temp[i] = a[i].get(t-1);
				}
			}
			boolean flag=true;
			for(int i=0; i<n; i++){
				flag&=temp[i]==temp[temp[i]-1];
			}
			if(flag){
				out.writeln(t);
				return;
			}
		}
		/*
		while(left<right){
			int mid = (left+right)/2;
			//System.out.println(mid);
			//int mid = 3;
			for(int i=0; i<n; i++){
				if(mid>a[i].size()){
					temp[i] = a[i].get(start[i]+(mid-start[i]+1)%len[i]-1);
				}else{
					temp[i] = a[i].get(mid-1);
				}
			}

			for(int i=0; i<n; i++)
				System.out.print(temp[i]+" ");
			System.out.println();

			boolean flag=true;
			for(int i=0; i<n; i++){
				flag&=temp[i]==temp[temp[i]-1];
			}
			if(flag)
				right=mid;
			else
				left=mid+1;
		}

		out.writeln(left);
		*/
	}

}

class InputReader {

	BufferedReader reader;
	StringTokenizer tokenizer;

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

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

		return tokenizer.nextToken();
	}

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

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

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

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

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

		return res;
	}

}

class OutputWriter {

	PrintWriter out;

	public OutputWriter(OutputStream stream) {
		out = new PrintWriter(
				new BufferedWriter(new OutputStreamWriter(stream)));
	}

	public void write(Object... o) {
		for (Object cur : o)
			out.print(cur);
	}

	public void writeln(Object... o) {
		write(o);
		out.println();
	}

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

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

}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main {
	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;

		// InputStream inputStream = new FileInputStream("input.txt");
		// OutputStream outputStream = new FileOutputStream("output.txt");

		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);

		TaskA solver = new TaskA();

		solver.solve(in, out);

		out.close();
	}
}

class TaskA {

	public void solve(InputReader in, OutputWriter out) {

		int n = in.nextInt();
		int[] f = in.nextIntArray(n);

		int[] len = new int[n];
		int[] start = new int[n];
		int[] u = new int[n];
		for(int i=0; i<n; i++){
			Arrays.fill(u, 0);
			int cur = f[i], step=1;
			while(u[cur-1]==0){
				u[cur-1]=step++;
				cur = f[cur-1];
			}
			len[i] = step-u[cur-1];
			start[i] = u[cur-1];
		}

		/*
		for(int i=0; i<n; i++){
			System.out.print(len[i]+"("+start[i]+") ");
		}
		System.out.println();
		*/

		int a=1;
		for(int i=0; i<n; i++)
			if(start[i]==1) a = lcm(a,len[i]);
		int b = 0;
		for(int i=0; i<n; i++)
			b = Math.max(b,start[i]-1);

		//System.out.println(a+" "+b);
		out.write(a*(b/a+1));
	}

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

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

}

class InputReader {

	BufferedReader reader;
	StringTokenizer tokenizer;

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

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

		return tokenizer.nextToken();
	}

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

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

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

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

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

		return res;
	}

}

class OutputWriter {

	PrintWriter out;

	public OutputWriter(OutputStream stream) {
		out = new PrintWriter(
				new BufferedWriter(new OutputStreamWriter(stream)));
	}

	public void write(Object... o) {
		for (Object cur : o)
			out.print(cur);
	}

	public void writeln(Object... o) {
		write(o);
		out.println();
	}

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

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

}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main {
	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;

		// InputStream inputStream = new FileInputStream("input.txt");
		// OutputStream outputStream = new FileOutputStream("output.txt");

		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);

		TaskA solver = new TaskA();

		solver.solve(in, out);

		out.close();
	}
}

class TaskA {

	public void solve(InputReader in, OutputWriter out) {

		int n = in.nextInt();
		int[] f = in.nextIntArray(n);
		for(int i=1; i<=100000; i++){
			boolean flag=true;
			for(int j=0; j<n; j++)
				flag&=f[j]==f[f[j]-1];
			if(flag){
				out.writeln(i);
				return;
			}
			for(int j=0; j<n; j++)
				f[j] = f[f[j]-1];
		}
	}

}

class InputReader {

	BufferedReader reader;
	StringTokenizer tokenizer;

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

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

		return tokenizer.nextToken();
	}

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

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

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

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

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

		return res;
	}

}

class OutputWriter {

	PrintWriter out;

	public OutputWriter(OutputStream stream) {
		out = new PrintWriter(
				new BufferedWriter(new OutputStreamWriter(stream)));
	}

	public void write(Object... o) {
		for (Object cur : o)
			out.print(cur);
	}

	public void writeln(Object... o) {
		write(o);
		out.println();
	}

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

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

}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main {
	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;

		// InputStream inputStream = new FileInputStream("input.txt");
		// OutputStream outputStream = new FileOutputStream("output.txt");

		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);

		TaskA solver = new TaskA();

		solver.solve(in, out);

		out.close();
	}
}

class TaskA {

	public void solve(InputReader in, OutputWriter out) {

		int n = in.nextInt();
		int[] f = in.nextIntArray(n);

		/*
		int n = 10;
		int[] f = new int[100];
		Random r = new Random();
		for(int i=0; i<n; i++)
			f[i] = r.nextInt(n-1+1)+1;
		*/

		ArrayList<Integer>[] a = new ArrayList[n];
		int[] len = new int[n];
		int[] start = new int[n];
		int[] u;

		for(int i=0; i<n; i++){
			a[i] = new ArrayList<Integer>();
			u = new int[n+1];
			int cur = f[i],step=1;
			while(u[cur]==0){
				a[i].add(cur);
				u[cur]=step++;
				cur = f[cur-1];
			}
			len[i] = step-u[cur];
			start[i] = u[cur];
		}

		int[] temp = new int[n];
		/*
		for(int t=1; ; t++){
			for(int i=0; i<n; i++){
				if(t>a[i].size()){
					temp[i] = a[i].get(start[i]+(t-start[i]+1)%len[i]-1);
				}else{
					temp[i] = a[i].get(t-1);
				}
			}
			boolean flag=true;
			for(int i=0; i<n; i++){
				flag&=temp[i]==temp[temp[i]-1];
			}
			if(flag){
				out.writeln(t);
				return;
			}
		}
		*/

		for(int i=0; i<n; i++)
			temp[i] = f[i];
		for(int i=1; i<=1000000; i++){
			/*
			for(int j=0; j<n; j++) temp[j] = f[j];
			for(int k=0; k<i-1; k++){
				for(int j=0; j<n; j++)
					temp[j] = f[temp[j]-1];
			}*/

			boolean flag=true;
			for(int j=0; j<n; j++)
				flag&=temp[j]==temp[temp[j]-1];
			if(flag){
				out.writeln(i);
				return;
			}

			for(int j=0; j<n; j++)
				temp[j] = f[temp[j]-1];

		}

	}

}

class InputReader {

	BufferedReader reader;
	StringTokenizer tokenizer;

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

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

		return tokenizer.nextToken();
	}

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

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

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

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

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

		return res;
	}

}

class OutputWriter {

	PrintWriter out;

	public OutputWriter(OutputStream stream) {
		out = new PrintWriter(
				new BufferedWriter(new OutputStreamWriter(stream)));
	}

	public void write(Object... o) {
		for (Object cur : o)
			out.print(cur);
	}

	public void writeln(Object... o) {
		write(o);
		out.println();
	}

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

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

}

import java.io.*;
import java.text.NumberFormat;
import java.util.*;

/**
 * Created by VIET ANH on 27/04/2015.
 */
public class test {

    private static int T;
    private static long oo=Long.MAX_VALUE;

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n=in.nextInt();
        int[] f=new int [300];
        int[] dau=new int[300];
        int vlcm=1;
        for (int i = 1; i <= n; i++) f[i] = in.nextInt();
        for (int i = 1; i <= n; i++) if (dau[i]==0){
            int x=i;
            int cir=0;
            while (dau[x]<2) {
                dau[x]++;
                if (dau[x]==2) cir++;
                x=f[x];
            }
            if (cir!=0) vlcm=lcm(vlcm,cir);
        }
        int maxpath=0;
        for (int i = 1; i <= n; i++) {
            int x=i;
            int path=0;
            while (dau[x] < 2) {
                path++;
                x = f[x];
            }
            maxpath=Math.max(maxpath,path);
        }
        if (vlcm<maxpath)
            if (maxpath%vlcm==0) vlcm=maxpath;
            else vlcm=(maxpath/vlcm+1)*vlcm;
        out.print(vlcm);
        out.close();
    }

    private static int lcm(int vlcm, int cir) {
        return vlcm*cir/gcd(vlcm,cir);
    }

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

}

import java.io.*;
import java.text.NumberFormat;
import java.util.*;

/**
 * Created by VIET ANH on 27/04/2015.
 */
public class test {

    private static int T;
    private static long oo=Long.MAX_VALUE;

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n=in.nextInt();
        int[] f=new int [300];
        int[] dau=new int[300];
        boolean[] incir=new boolean[300];
        int vlcm=1;
        for (int i = 1; i <= n; i++) f[i] = in.nextInt();
        int dem=0;
        for (int i = 1; i <= n; i++) {
            int x=i;
            int cir=0;
            dem++;
            while (dau[x] == 0) {
                dau[x] = dem;
                x=f[x];
            }
            if (dau[x]!=dem) continue;
            int y=x;
            do{
                cir++;
                incir[y]=true;
                y=f[y];
            } while (y!=x);
            if (cir!=0) vlcm=lcm(vlcm,cir);
        }
        int maxpath=0;
        for (int i = 1; i <= n; i++) {
            int x=i;
            int path=0;
            while (!incir[x]) {
                path++;
                x = f[x];
            }
            maxpath=Math.max(maxpath,path);
        }
        if (vlcm<maxpath)
            if (maxpath%vlcm==0) vlcm=maxpath;
            else vlcm=(maxpath/vlcm+1)*vlcm;
        out.print(vlcm);
        out.close();
    }

    private static int lcm(int vlcm, int cir) {
        return vlcm*cir/gcd(vlcm,cir);
    }

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

}

import java.io.*;
import java.text.NumberFormat;
import java.util.*;

/**
 * Created by VIET ANH on 27/04/2015.
 */
public class test {

    private static int T;
    private static long oo=Long.MAX_VALUE;

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n=in.nextInt();
        int[] f=new int [300];
        int[] dau=new int[300];
        boolean[] node=new boolean[300];
        int vlcm=1;
        for (int i = 1; i <= n; i++) f[i] = in.nextInt();
        int dem=0;
        for (int i = 1; i <= n; i++) {
            int x=i;
            int cir=0;
            dem++;
            while (dau[x] == 0) {
                dau[x] = dem;
                x=f[x];
            }
            if (dau[x]!=dem) continue;
            int y=x;
            node[x]=true;
            do{
                cir++;
                y=f[y];
            } while (y!=x);
            if (cir!=0) vlcm=lcm(vlcm,cir);
        }
        int maxpath=0;
        for (int i = 1; i <= n; i++) {
            int x=i;
            int path=0;
            while (!node[x]) {
                path++;
                x = f[x];
            }
            maxpath=Math.max(maxpath,path);
        }
        if (vlcm<maxpath)
            if (maxpath%vlcm==0) vlcm=maxpath;
            else vlcm=(maxpath/vlcm+1)*vlcm;
        out.print(vlcm);
        out.close();
    }

    private static int lcm(int vlcm, int cir) {
        return vlcm*cir/gcd(vlcm,cir);
    }

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

}

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

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

class TaskC {
    int[] a;
    public void solve(int testNumber, Reader in, PrintWriter out) {
        int n = in.ni();
        a = new int[n];
        for(int i = 0; i < n; i++) {
            a[i] = in.ni() - 1;
        }
        int max = 1;
        boolean[] used = new boolean[n];
        int[] cycle = new int[n];
        int[] len = new int[n];
        for(int i = 0; i < n; i++) {
            Arrays.fill(used, false);
            int cur = i;
            int edges = 0;
            while(true) {
                if(a[cur] == cur || used[cur]) {
                    cycle[i] = cur;
                    len[i] = edges;
                    break;
                }
                used[cur] = true;
                cur = a[cur];
                edges++;
            }
        }
        for(int i = 0; i < n; i++) {
            max = Math.max(len[i], max);
        }
//        out.println(max);
//        out.println(Arrays.toString(cycle));
        for(int i = 1; i <= max; i++) {
            boolean success = true;
            for(int j = 0; j < n; j++) {
                int leftValue, rightValue;
                leftValue = j;
                rightValue = j;
                for(int z = 0; z < i; z++) {
                    leftValue = a[leftValue];
                }
                for(int z = 0; z < 2 * i; z++) {
                    rightValue = a[rightValue];
                }
                if(leftValue != rightValue) {
                    success = false;
                }
            }
            if(success) {
                out.println(i);
                return;
            }
        }

        int[] cycleLen = new int[n];
        for(int i = 0; i < n; i++) {
            int cur = a[cycle[i]];
            int cnt = 1;
            while(true) {
                if(cur == cycle[i]) {
                    cycleLen[i] = cnt;
                    break;
                }
                cur = a[cur];
                cnt++;
            }
        }

        long lcm = cycleLen[0];
        for(int i = 1; i < n; i++) {
            lcm = Helper.lcm(lcm, a[i]);
        }

        if(max > lcm) {
            out.println(max % lcm == 0 ? lcm * (max / lcm) : lcm * (max / lcm + 1));
        } else {
            out.println(lcm);
        }

    }
}

class Reader {
    private BufferedReader in;
    private StringTokenizer st = new StringTokenizer("");
    private String delim = " ";

    public Reader(InputStream in) {
        this.in = new BufferedReader(new InputStreamReader(in));
    }

    public String next() {
        if (!st.hasMoreTokens()) {
            st = new StringTokenizer(rl());
        }
        return st.nextToken(delim);
    }

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

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

}

class Helper {

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

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

}

import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;

import static java.lang.Math.*;

// Solution is at the bottom of code

public class C implements Runnable{

	final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

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

	public static void main(String[] args){
		new Thread(null, new C(), "", 128 * (1L << 20)).start();
	}

	/////////////////////////////////////////////////////////////////////

	void init() throws FileNotFoundException{
		Locale.setDefault(Locale.US);

		if (ONLINE_JUDGE){
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new OutputWriter(System.out);
		}else{
			in = new BufferedReader(new FileReader("input.txt"));
			out = new OutputWriter("output.txt");
		}
	}

	////////////////////////////////////////////////////////////////

	long timeBegin, timeEnd;

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

	void debug(Object... objects){
		if (ONLINE_JUDGE){
			for (Object o: objects){
				System.err.println(o.toString());
			}
		}
	}

	/////////////////////////////////////////////////////////////////////

	public void run(){
		try{
			timeBegin = System.currentTimeMillis();
			Locale.setDefault(Locale.US);

			init();
			solve();

			out.close();
			time();
		}catch (Exception e){
			e.printStackTrace(System.err);
			System.exit(-1);
		}
	}

	/////////////////////////////////////////////////////////////////////

	String delim = " ";

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

		return tok.nextToken(delim);
	}

	String readLine() throws IOException{
		return in.readLine();
	}

	/////////////////////////////////////////////////////////////////

	final char NOT_A_SYMBOL = '\0';

	char readChar() throws IOException{
		int intValue = in.read();

		if (intValue == -1){
			return NOT_A_SYMBOL;
		}

		return (char) intValue;
	}

	char[] readCharArray() throws IOException{
		return readLine().toCharArray();
	}

	/////////////////////////////////////////////////////////////////

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

	int[] readIntArray(int size) throws IOException {
		int[] array = new int[size];

		for (int index = 0; index < size; ++index){
			array[index] = readInt();
		}

		return array;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = readInt();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] readIntArrayWithDecrease(int size) throws IOException {
		int[] array = readIntArray(size);

		for (int i = 0; i < size; ++i) {
			array[i]--;
		}

		return array;
	}

	///////////////////////////////////////////////////////////////////

	int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException {
		int[][] matrix = new int[rowsCount][];

		for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
			matrix[rowIndex] = readIntArray(columnsCount);
		}

		return matrix;
	}

	int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException {
		int[][] matrix = new int[rowsCount][];

		for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
			matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
		}

		return matrix;
	}

	///////////////////////////////////////////////////////////////////

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

	long[] readLongArray(int size) throws IOException{
		long[] array = new long[size];

		for (int index = 0; index < size; ++index){
			array[index] = readLong();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

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

	double[] readDoubleArray(int size) throws IOException{
		double[] array = new double[size];

		for (int index = 0; index < size; ++index){
			array[index] = readDouble();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

	BigInteger readBigInteger() throws IOException {
		return new BigInteger(readString());
	}

	BigDecimal readBigDecimal() throws IOException {
		return new BigDecimal(readString());
	}

	/////////////////////////////////////////////////////////////////////

	Point readPoint() throws IOException{
		int x = readInt();
		int y = readInt();
		return new Point(x, y);
	}

	Point[] readPointArray(int size) throws IOException{
		Point[] array = new Point[size];

		for (int index = 0; index < size; ++index){
			array[index] = readPoint();
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
	throws IOException{
		@SuppressWarnings("unchecked")
		List<Integer>[] graph = new List[vertexNumber];

		for (int index = 0; index < vertexNumber; ++index){
			graph[index] = new ArrayList<Integer>();
		}

		while (edgeNumber-- > 0){
			int from = readInt() - 1;
			int to = readInt() - 1;

			graph[from].add(to);
			graph[to].add(from);
		}

		return graph;
	}

	/////////////////////////////////////////////////////////////////////

	static class IntIndexPair {

		static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() {

			@Override
			public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
				int value1 = indexPair1.value;
				int value2 = indexPair2.value;

				if (value1 != value2) return value1 - value2;

				int index1 = indexPair1.index;
				int index2 = indexPair2.index;

				return index1 - index2;
			}
		};

		static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() {

			@Override
			public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
				int value1 = indexPair1.value;
				int value2 = indexPair2.value;

				if (value1 != value2) return -(value1 - value2);

				int index1 = indexPair1.index;
				int index2 = indexPair2.index;

				return index1 - index2;
			}
		};

		int value, index;

		public IntIndexPair(int value, int index) {
			super();
			this.value = value;
			this.index = index;
		}

		public int getRealIndex() {
			return index + 1;
		}
	}

	IntIndexPair[] readIntIndexArray(int size) throws IOException {
		IntIndexPair[] array = new IntIndexPair[size];

		for (int index = 0; index < size; ++index) {
			array[index] = new IntIndexPair(readInt(), index);
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	static class OutputWriter extends PrintWriter {

		final int DEFAULT_PRECISION = 12;

		protected int precision;
		protected String format, formatWithSpace;

		{
			precision = DEFAULT_PRECISION;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		public OutputWriter(OutputStream out) {
			super(out);
		}

		public OutputWriter(String fileName) throws FileNotFoundException {
			super(fileName);
		}

		public int getPrecision() {
			return precision;
		}

		public void setPrecision(int precision) {
			precision = max(0, precision);
			this.precision = precision;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		private String createFormat(int precision){
			return "%." + precision + "f";
		}

		@Override
		public void print(double d){
			printf(format, d);
		}

		public void printWithSpace(double d){
			printf(formatWithSpace, d);
		}

		public void printAll(double...d){
			for (int i = 0; i < d.length - 1; ++i){
				printWithSpace(d[i]);
			}

			print(d[d.length - 1]);
		}

		@Override
		public void println(double d){
			printlnAll(d);
		}

		public void printlnAll(double... d){
			printAll(d);
			println();
		}
	}

	/////////////////////////////////////////////////////////////////////

	static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
	static final int[][] steps8 = {
			{-1, 0}, {1, 0}, {0, -1}, {0, 1},
			{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
	};

	static final boolean check(int index, int lim){
		return (0 <= index && index < lim);
	}

	/////////////////////////////////////////////////////////////////////

	static final boolean checkBit(int mask, int bit){
		return (mask & (1 << bit)) != 0;
	}

	/////////////////////////////////////////////////////////////////////

	static final long getSum(int[] array) {
		long sum = 0;
		for (int value: array) {
			sum += value;
		}

		return sum;
	}

	static final Point getMinMax(int[] array) {
		int min = array[0];
		int max = array[0];

		for (int index = 0, size = array.length; index < size; ++index, ++index) {
			int value = array[index];

			if (index == size - 1) {
				min = min(min, value);
				max = max(max, value);
			} else {
				int otherValue = array[index + 1];

				if (value <= otherValue) {
					min = min(min, value);
					max = max(max, otherValue);
				} else {
					min = min(min, otherValue);
					max = max(max, value);
				}
			}
		}

		return new Point(min, max);
	}

	/////////////////////////////////////////////////////////////////////

	void solve() throws IOException {
		int n = readInt();
		int[] f = readIntArrayWithDecrease(n);

		int[][] fs = new int[n][3 * n];
		for (int i = 0; i < n; ++i) {
			fs[i][0] = f[i];
			for (int k = 1; k < 3 * n; ++k) {
				fs[i][k] = f[fs[i][k-1]];
			}
		}

		int[] periods = new int[n];
		int[] starts = new int[n];

		for (int i = 0; i < n; ++i) {
			int[] lasts = new int[n];
			Arrays.fill(lasts, -1);

			for (int j = 1; j < fs[i].length; ++j) {
				if (lasts[fs[i][j]] != -1) {
					starts[i] = lasts[fs[i][j]];
					periods[i] = j - starts[i];
					break;
				} else {
					lasts[fs[i][j]] = j;
				}
//				if (fs[i][j] == fs[i][0]) {
//					periods[i] = j;
//					starts[i] = 0;
//
//					break;
//				}
//
//				if (fs[i][j] == fs[i][j-1]) {
//					periods[i] = 1;
//					starts[i] = j - 1;
//
//					break;
//				}
			}
		}

		long lcmPeriod = periods[0];
		int maxStart = starts[0] + 1;

		for (int i = 1; i < n; ++i) {
			lcmPeriod = lcm(lcmPeriod, periods[i]);
			maxStart = max(maxStart, starts[i] + 1);
		}

		long minMultiply = (maxStart - 1) / lcmPeriod + 1;
		long minPeriod = minMultiply * lcmPeriod;

		out.println(minPeriod);
	}

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

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

import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
import java.util.InputMismatchException;
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();
	}
}

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

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

    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.readInt();
        int[] f = new int[n];
        for (int i = 0; i < n; ++i) {
            f[i] = in.readInt() - 1;
        }
        long res = 1;
        int[] c = new int[n];
        Arrays.fill(c, -1);
        for (int i = 0; i < n; ++i) {
            c[i] = calc(i, f);
        }
        for (int i = 0; i < n; ++i) {
            res = lcm(res, Math.max(1, c[i]));
        }
        out.println(res);
    }

    private int calc(int i, int[] f) {
        boolean[] vis = new boolean[f.length];
        if (f[i] == i) return 0;
        int res = 0;
        vis[i] = true;
        while (true) {
            res++;
            i = f[i];
            if (vis[i] == true) break;
            vis[i] = true;
        }
        if (f[i] == i) res--;
        return res;
    }

}

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 UnknownError();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new UnknownError();
            }
            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();
        } else if (c == '+') {
            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 static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

}

import java.util.HashMap;
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int min = 1, z = 1;

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

        for (int i = 1; i<=n; i++) {
            HashMap<Integer, Integer> hs = new HashMap();
            hs.put(i, 0);
            int next = a[i];
            int k = 1;
            while (!hs.containsKey(next)) {
                hs.put(next, k);
                k++;
                next = a[next];
            }
            if (next == i) {
                //System.out.println(i + " A " + k);
                z = lcm(z,k);
            } else if ((k = hs.get(next)) > min) {
                //System.out.println(i + " B " + k);
                min = k;
            }
        }
        System.out.println(min%z == 0? min:(min/z+1)*z);
    }

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

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

import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.io.InputStream;
import java.util.Collection;
import java.math.BigInteger;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Queue;
import java.io.IOException;

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

class TaskC
{
    int n;
    ArrayList<Integer> G[], revG[];
    long ans;
    SCC scc;
    int sizeComp[];
    int next[];

    public void solve(int testNumber, FastReader in, PrintWriter out)
    {
        n = in.ni ();
        next = new int[n];
        G = new ArrayList[n];
        revG = new ArrayList[n];
        for (int i = 0; i < n; i++)
        {
            G[i] = new ArrayList<Integer> ();
            revG[i] = new ArrayList<Integer> ();
        }
        for (int i = 0; i < n; i++)
        {
            int x = in.ni () - 1;
            next[i] = x;
            G[i].add (x);
            revG[x].add (i);
        }
        scc = new SCC ();
        scc.getSCC (G, revG);
        ans = 0;
        sizeComp = new int[scc.numComp];
        int compressed[] = new int[scc.numComp];
        Arrays.fill (compressed, -1);
        for (int i = 0; i < n; i++)
        {
            int x = scc.comp[i];
            int y = scc.comp[next[i]];
            //edge from x to y in compressed graph
            if (x != y)
            {
                compressed[x] = y;
            }
            sizeComp[x]++;
        }
        for (int i = 0; i < scc.numComp; i++)
        {
            ans = Math.max (ans, sizeComp[i]);
        }
        //back bfs
        int minDist[] = new int[scc.numComp];
        int size[] = new int[scc.numComp];
        Arrays.fill (minDist, -1);
        Queue<Integer> queue = new ArrayDeque<Integer> ();
        for (int i = 0; i < scc.numComp; i++)
        {
            if (compressed[i] == -1)
            {
                minDist[i] = 0;
                size[i] = sizeComp[i];
                queue.add (i);
            }
        }
        while (!queue.isEmpty ())
        {
            int x = queue.poll ();
            if (minDist[x] != 0)
            {
                ans = Math.max (ans, getNext (minDist[x], size[x]));
            }
            for (int i = 0; i < scc.numComp; i++)
            {
                if (compressed[i] == x)
                {
                    queue.add (i);
                    minDist[i] = minDist[x] + 1;
                    size[i] = size[x];
                }
            }
        }
        out.println (ans);

//        int n = in.ni ();
//        int next[] = new int[n];
//        int cur[] = new int[n];
//        for (int i = 0; i < n; i++)
//        {
//            cur[i] = next[i] = in.ni () - 1;
//        }
//        int k = 1;
//        int temp[] = new int[n];
//        while (!idempotent (cur))
//        {
////            if (k == 8)
////            {
////                for (int i = 0; i < n; i++)
////                {
////                    out.println ((i + 1) + "->" + (cur[i] + 1));
////                }
////            }
//            k++;
//            for (int i = 0; i < n; i++)
//            {
//                temp[i] = next[cur[i]];
//            }
//            int t[] = temp;
//            temp = cur;
//            cur = t;
//        }
//        out.println (k);
    }

    private long getNext(int x, int y)
    {
        long k = (x % y == 0 ? x / y : (x / y) + 1);
        return k * y;
    }

//    private int getMinK(int lo, int hi, int[] next)
//    {
//        if (lo > hi)
//        {
//            return Integer.MAX_VALUE;
//        }
//        int mid = (lo + hi) / 2;
//        if (okay (mid, next))
//        {
//            return Math.min (getMinK (lo, mid - 1, next), mid);
//        }
//        return getMinK (mid + 1, hi, next);
//    }

}

class SCC
{
    public int numComp; //number of SCC
    public int comp[];  //component number of vertex i from [0, numComp)
    int n;
    ArrayList<Integer> revG[];
    /*
    takes as input graph and its reverse
    Kosaraju two pass algorithm
    for explanation see techniques
    Also note that we have proceeded in topological order of actual Graph while calculation comp[]
     */
    public void getSCC(ArrayList<Integer> G[], ArrayList<Integer> revG[])
    {
        this.revG = revG;
        numComp = 0;
        n = G.length;
        comp = new int[n];
        Arrays.fill (comp, -1);
        int revPostOrder[] = new TopoSort ().topoSort (G); //actually not topo order, coz graph is cyclic
        for (int x : revPostOrder)
        {
            if (comp[x] == -1)
            {
                dfs (x);
                numComp++;
            }
        }
    }

    private void dfs(int i)
    {
        comp[i] = numComp;
        for (int v : revG[i])
        {
            if (comp[v] != -1)
            {
                continue;
            }
            dfs (v);
        }
    }
}

class FastReader
{

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

    public FastReader(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 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;
    }

    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);
    }
}

class TopoSort
{
    boolean done[];
    int n;
    ArrayList<Integer> adjList[];
    public int topoOrder[];
    int revCtr;
    /*
    returns reversed post order of graph
    graph should be dag for order to be topologically sorted
     */
    public int[] topoSort(ArrayList<Integer> adjList[])
    {
        this.adjList = adjList;
        n = adjList.length;
        done = new boolean[n];
        topoOrder = new int[n];
        revCtr = n-1;
        for (int i = 0; i < n; i++)
        {
            if (!done[i])
            {
                done[i] = true;
                dfs (i);
            }
        }
        return topoOrder;
    }

    private void dfs(int i)
    {
        for (int v : adjList[i])
        {
            if(!done[v])
            {
                done[v] = true;
                dfs (v);
            }
        }
        topoOrder[revCtr--] = i;
    }
}

import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.io.InputStream;
import java.util.Random;
import java.util.Collection;
import java.math.BigInteger;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Queue;
import java.io.IOException;

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

class TaskC
{
    int n;
    ArrayList<Integer> G[], revG[];
    long ans;
    SCC scc;
    int sizeComp[];
    int next[];

    public void solve(int testNumber, FastReader in, PrintWriter out)
    {
        n = in.ni ();
        next = new int[n];
        G = new ArrayList[n];
        revG = new ArrayList[n];
        for (int i = 0; i < n; i++)
        {
            G[i] = new ArrayList<Integer> ();
            revG[i] = new ArrayList<Integer> ();
        }
        for (int i = 0; i < n; i++)
        {
            int x = in.ni () - 1;
            next[i] = x;
            G[i].add (x);
            revG[x].add (i);
        }
        scc = new SCC ();
        scc.getSCC (G, revG);
        ans = 0;
        sizeComp = new int[scc.numComp];
        int compressed[] = new int[scc.numComp];
        Arrays.fill (compressed, -1);
        for (int i = 0; i < n; i++)
        {
            int x = scc.comp[i];
            int y = scc.comp[next[i]];
            //edge from x to y in compressed graph
            if (x != y)
            {
                compressed[x] = y;
            }
            sizeComp[x]++;
        }
        ans = sizeComp[0];
        for (int i = 0; i < scc.numComp; i++)
        {
            ans = lcm (ans, sizeComp[i]);
        }
        //back bfs
        int minDist[] = new int[scc.numComp];
        int size[] = new int[scc.numComp];
        Arrays.fill (minDist, -1);
        Queue<Integer> queue = new ArrayDeque<Integer> ();
        for (int i = 0; i < scc.numComp; i++)
        {
            if (compressed[i] == -1)
            {
                minDist[i] = 0;
                size[i] = sizeComp[i];
                queue.add (i);
            }
        }
        while (!queue.isEmpty ())
        {
            int x = queue.poll ();
            if (minDist[x] != 0)
            {
                ans = getNext (minDist[x], ans);
            }
            for (int i = 0; i < scc.numComp; i++)
            {
                if (compressed[i] == x)
                {
                    queue.add (i);
                    minDist[i] = minDist[x] + 1;
                    size[i] = size[x];
                }
            }
        }
        out.println (ans);

//        int n = in.ni ();
//        int next[] = new int[n];
//        int cur[] = new int[n];
//        for (int i = 0; i < n; i++)
//        {
//            cur[i] = next[i] = in.ni () - 1;
//        }
//        int k = 1;
//        int temp[] = new int[n];
//        while (!idempotent (cur))
//        {
////            if (k == 8)
////            {
////                for (int i = 0; i < n; i++)
////                {
////                    out.println ((i + 1) + "->" + (cur[i] + 1));
////                }
////            }
//            k++;
//            for (int i = 0; i < n; i++)
//            {
//                temp[i] = next[cur[i]];
//            }
//            int t[] = temp;
//            temp = cur;
//            cur = t;
//        }
//        out.println (k);
    }

    private long lcm(long x, long y)
    {
        return (x / MathUtils.gcd (x, y)) * y;
    }

    private long getNext(long x, long y)
    {
        long k = (x % y == 0 ? x / y : (x / y) + 1);
        return k * y;
    }
//    private boolean idempotent(int[] cur)
//    {
//        for (int i = 0; i < cur.length; i++)
//        {
//            if (cur[cur[i]] != cur[i])
//            {
//                return false;
//            }
//        }
//        return true;
//    }

}

class SCC
{
    public int numComp; //number of SCC
    public int comp[];  //component number of vertex i from [0, numComp)
    int n;
    ArrayList<Integer> revG[];
    /*
    takes as input graph and its reverse
    Kosaraju two pass algorithm
    for explanation see techniques
    Also note that we have proceeded in topological order of actual Graph while calculation comp[]
     */
    public void getSCC(ArrayList<Integer> G[], ArrayList<Integer> revG[])
    {
        this.revG = revG;
        numComp = 0;
        n = G.length;
        comp = new int[n];
        Arrays.fill (comp, -1);
        int revPostOrder[] = new TopoSort ().topoSort (G); //actually not topo order, coz graph is cyclic
        for (int x : revPostOrder)
        {
            if (comp[x] == -1)
            {
                dfs (x);
                numComp++;
            }
        }
    }

    private void dfs(int i)
    {
        comp[i] = numComp;
        for (int v : revG[i])
        {
            if (comp[v] != -1)
            {
                continue;
            }
            dfs (v);
        }
    }
}

class FastReader
{

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

    public FastReader(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 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;
    }

    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);
    }
}

class MathUtils
{
    public static long gcd(long big, long small) // O(log min(a, b))
    {
        if (small == 0)
            return big;
        return gcd(small, big % small); // big%small<=small
    }

    // NCR DP
    // O(n*n) precomputation -> dp, no overflow

    /*factor sieve -> O(n/2) memory      */

    //    public static long fastMult( long a, long b, long m )
//    {
//        //from http://apps.topcoder.com/forums/?module=RevisionHistory&messageID=1221302
//        if(a>m)
//            a=a%m;
//        if(b>m)
//            b=b%m;
//        long ret = 0;
//        if(a<b)
//        {
//            long t = a;
//            a = b;
//            b = t;
//        }
//        while(b>0)
//        {
//            while(a<m)
//            {
//                if((b&1) != 0)
//                    ret += a;
//                a<<=1;
//                b>>=1;
//            }
//            a-=m;
//            while(ret>=m)
//                ret-=m;
//            if(a<b)
//            {
//                long t = a;
//                a = b;
//                b = t;
//            }
//        }
//        return ret;
//    }

}

class TopoSort
{
    boolean done[];
    int n;
    ArrayList<Integer> adjList[];
    public int topoOrder[];
    int revCtr;
    /*
    returns reversed post order of graph
    graph should be dag for order to be topologically sorted
     */
    public int[] topoSort(ArrayList<Integer> adjList[])
    {
        this.adjList = adjList;
        n = adjList.length;
        done = new boolean[n];
        topoOrder = new int[n];
        revCtr = n-1;
        for (int i = 0; i < n; i++)
        {
            if (!done[i])
            {
                done[i] = true;
                dfs (i);
            }
        }
        return topoOrder;
    }

    private void dfs(int i)
    {
        for (int v : adjList[i])
        {
            if(!done[v])
            {
                done[v] = true;
                dfs (v);
            }
        }
        topoOrder[revCtr--] = i;
    }
}

import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.io.InputStream;
import java.util.Collection;
import java.math.BigInteger;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Queue;
import java.io.IOException;

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

class TaskC
{
    int n;
    ArrayList<Integer> G[], revG[];
    int ans;
    SCC scc;
    int sizeComp[];
    int next[];
    public void solve(int testNumber, FastReader in, PrintWriter out)
    {
        n = in.ni ();
        next = new int[n];
        G = new ArrayList[n];
        revG = new ArrayList[n];
        for (int i = 0; i < n; i++)
        {
            G[i] = new ArrayList<Integer> ();
            revG[i] = new ArrayList<Integer> ();
        }
        for (int i = 0; i < n; i++)
        {
            int x = in.ni () - 1;
            next[i] = x;
            G[i].add (x);
            revG[x].add (i);
        }
        scc = new SCC ();
        scc.getSCC (G, revG);
        ans = 0;
        sizeComp = new int[scc.numComp];
        int compressed[] = new int[scc.numComp];
        Arrays.fill (compressed, -1);
        for (int i = 0; i < n; i++)
        {
            int x = scc.comp[i];
            int y = scc.comp[next[i]];
            //edge from x to y in compressed graph
            if (x != y)
            {
                compressed[x] = y;
            }
            sizeComp[x]++;
        }
        for (int i = 0; i < scc.numComp; i++)
        {
            ans = Math.max (ans, sizeComp[i]);
        }
        //back bfs
        int minDist[] = new int[scc.numComp];
        Arrays.fill (minDist, -1);
        Queue<Integer> queue = new ArrayDeque<Integer> ();
        for (int i = 0; i < scc.numComp; i++)
        {
            if (compressed[i] == -1)
            {
                minDist[i] = 0;
                queue.add (i);
            }
        }
        while (!queue.isEmpty ())
        {
            int x = queue.poll ();
            ans = Math.max (ans, minDist[x]);
            for (int i = 0; i < scc.numComp; i++)
            {
                if (compressed[i] == x)
                {
                    queue.add (i);
                    minDist[i] = minDist[x] + 1;
                }
            }
        }
        out.println (ans);

//        int n = in.ni ();
//        int next[] = new int[n];
//        int cur[] = new int[n];
//        for (int i = 0; i < n; i++)
//        {
//            next[i] = in.ni () - 1;
//        }
//        out.println (getMinK (1, (int)1e9, next));

    }

//    private int getMinK(int lo, int hi, int[] next)
//    {
//        if (lo > hi)
//        {
//            return Integer.MAX_VALUE;
//        }
//        int mid = (lo + hi) / 2;
//        if (okay (mid, next))
//        {
//            return Math.min (getMinK (lo, mid - 1, next), mid);
//        }
//        return getMinK (mid + 1, hi, next);
//    }

//    private boolean okay(int mid, int[] next)
//    {
//        if (mid == 1)
//        {
//
//        }
//    }
//
//    private boolean idempotent(int[] cur)
//    {
//        for (int i = 0; i < cur.length; i++)
//        {
//            if (cur[cur[i]] != cur[i])
//            {
//                return false;
//            }
//        }
//        return true;
//    }

}

class SCC
{
    public int numComp; //number of SCC
    public int comp[];  //component number of vertex i from [0, numComp)
    int n;
    ArrayList<Integer> revG[];
    /*
    takes as input graph and its reverse
    Kosaraju two pass algorithm
    for explanation see techniques
    Also note that we have proceeded in topological order of actual Graph while calculation comp[]
     */
    public void getSCC(ArrayList<Integer> G[], ArrayList<Integer> revG[])
    {
        this.revG = revG;
        numComp = 0;
        n = G.length;
        comp = new int[n];
        Arrays.fill (comp, -1);
        int revPostOrder[] = new TopoSort ().topoSort (G); //actually not topo order, coz graph is cyclic
        for (int x : revPostOrder)
        {
            if (comp[x] == -1)
            {
                dfs (x);
                numComp++;
            }
        }
    }

    private void dfs(int i)
    {
        comp[i] = numComp;
        for (int v : revG[i])
        {
            if (comp[v] != -1)
            {
                continue;
            }
            dfs (v);
        }
    }
}

class FastReader
{

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

    public FastReader(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 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;
    }

    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);
    }
}

class TopoSort
{
    boolean done[];
    int n;
    ArrayList<Integer> adjList[];
    public int topoOrder[];
    int revCtr;
    /*
    returns reversed post order of graph
    graph should be dag for order to be topologically sorted
     */
    public int[] topoSort(ArrayList<Integer> adjList[])
    {
        this.adjList = adjList;
        n = adjList.length;
        done = new boolean[n];
        topoOrder = new int[n];
        revCtr = n-1;
        for (int i = 0; i < n; i++)
        {
            if (!done[i])
            {
                done[i] = true;
                dfs (i);
            }
        }
        return topoOrder;
    }

    private void dfs(int i)
    {
        for (int v : adjList[i])
        {
            if(!done[v])
            {
                done[v] = true;
                dfs (v);
            }
        }
        topoOrder[revCtr--] = i;
    }
}

import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class A {
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        // Scanner scan = new Scanner(System.in);
        // PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(bf.readLine());
        StringTokenizer st = new StringTokenizer(bf.readLine());
        int[][] a = new int[n+1][n];
        for(int i=0; i<n; i++) a[0][i] = i+1;
        for(int i=0; i<n; i++) a[1][i] = Integer.parseInt(st.nextToken());
        int[] b = new int[n];
        for(int i=0; i<n; i++) {
            int counter = 1;
            int val = i;
            while(a[1][val]-1 != i) {
                counter++;
                val = a[1][val]-1;
                if(counter > 300) {
                    counter = Integer.MAX_VALUE;
                    break;
                }
            }
            b[i] = counter;
        }
        long[] ans = new long[n+1];
        Arrays.fill(ans, 1);
        for(int i=1; i<=n; i++) {
            for(int j=0; j<n; j++) {
                a[i][j] = a[1][a[i-1][j]-1];
                ans[i] = lcm(ans[i], b[a[i][j]-1]);
                if(ans[i] > 300) break;
            }
            if(i % ans[i] == 0) {
                System.out.println(i);
                System.exit(0);
            }
        }
        // int n = Integer.parseInt(st.nextToken());
        // int n = scan.nextInt();

        // out.close(); System.exit(0);
    }
    public static long gcd(long a, long b) {
        if(b == 0) return a;
        return gcd(b, a % b);
    }
    public static long lcm(long a, long b) {
        return ((1L*a*b)/gcd(a, b));
    }
}

import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class A {
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        // Scanner scan = new Scanner(System.in);
        // PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(bf.readLine());
        StringTokenizer st = new StringTokenizer(bf.readLine());
        int[][] a = new int[401][n];
        for(int i=0; i<n; i++) a[0][i] = i+1;
        for(int i=0; i<n; i++) a[1][i] = Integer.parseInt(st.nextToken());
        int[] b = new int[n];
        for(int i=0; i<n; i++) {
            int counter = 1;
            int val = i;
            while(a[1][val]-1 != i) {
                counter++;
                val = a[1][val]-1;
                if(counter > 400) {
                    counter = 1007;
                    break;
                }
            }
            b[i] = counter;
        }
        long[] ans = new long[401];
        Arrays.fill(ans, 1);
        for(int i=1; i<=400; i++)
            for(int j=0; j<n; j++)
                a[i][j] = a[1][a[i-1][j]-1];
        for(int i=1; i<=400; i++) {
            for(int j=0; j<n; j++) {
                //System.out.println(n + " " + i + " " + j + " " + a[i-1][j]);
                ans[i] = lcm(ans[i], b[a[i][j]-1]);
                if(ans[i] > 400) break;
            }
            if(i % ans[i] == 0) {
                System.out.println(i);
                System.exit(0);
            }
        }
        // int n = Integer.parseInt(st.nextToken());
        // int n = scan.nextInt();

        // out.close(); System.exit(0);
    }
    public static long gcd(long a, long b) {
        if(b == 0) return a;
        return gcd(b, a % b);
    }
    public static long lcm(long a, long b) {
        return ((1L*a*b)/gcd(a, b));
    }
}

import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class A {
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        // Scanner scan = new Scanner(System.in);
        // PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(bf.readLine());
        StringTokenizer st = new StringTokenizer(bf.readLine());
        int[][] a = new int[n+1][n];
        for(int i=0; i<n; i++) a[0][i] = i+1;
        for(int i=0; i<n; i++) a[1][i] = Integer.parseInt(st.nextToken());
        int[] b = new int[n];
        for(int i=0; i<n; i++) {
            int counter = 1;
            int val = i;
            while(a[1][val]-1 != i) {
                counter++;
                val = a[1][val]-1;
                if(counter > 300) {
                    counter = 1007;
                    break;
                }
            }
            b[i] = counter;
        }
        long[] ans = new long[n+1];
        Arrays.fill(ans, 1);
        for(int i=1; i<=n; i++)
            for(int j=0; j<n; j++)
                a[i][j] = a[1][a[i-1][j]-1];
        for(int i=1; i<=n; i++) {
            for(int j=0; j<n; j++) {
                //System.out.println(n + " " + i + " " + j + " " + a[i-1][j]);
                ans[i] = lcm(ans[i], b[a[i][j]-1]);
                if(ans[i] > 300) break;
            }
            if(i % ans[i] == 0) {
                System.out.println(i);
                System.exit(0);
            }
        }
        // int n = Integer.parseInt(st.nextToken());
        // int n = scan.nextInt();

        // out.close(); System.exit(0);
    }
    public static long gcd(long a, long b) {
        if(b == 0) return a;
        return gcd(b, a % b);
    }
    public static long lcm(long a, long b) {
        return ((1L*a*b)/gcd(a, b));
    }
}

import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class A {
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        // Scanner scan = new Scanner(System.in);
        // PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(bf.readLine());
        StringTokenizer st = new StringTokenizer(bf.readLine());
        int[][] a = new int[n+1][n];
        for(int i=0; i<n; i++) a[0][i] = i+1;
        for(int i=0; i<n; i++) a[1][i] = Integer.parseInt(st.nextToken());
        int[] b = new int[n];
        for(int i=0; i<n; i++) {
            int counter = 1;
            int val = i;
            while(a[1][val]-1 != i) {
                counter++;
                val = a[1][val]-1;
                if(counter > 300) {
                    counter = Integer.MAX_VALUE;
                    break;
                }
            }
            b[i] = counter;
        }
        long[] ans = new long[n+1];
        Arrays.fill(ans, 1);
        for(int i=1; i<=n; i++) {
            for(int j=0; j<n; j++) {
                a[i][j] = a[1][a[i-1][j]-1];
                ans[i] = lcm(ans[i], b[a[i][j]-1]);
            }
            if(i % ans[i] == 0) {
                System.out.println(i);
                System.exit(0);
            }
        }
        // int n = Integer.parseInt(st.nextToken());
        // int n = scan.nextInt();

        // out.close(); System.exit(0);
    }
    public static long gcd(long a, long b) {
        if(b == 0) return a;
        return gcd(b, a % b);
    }
    public static long lcm(long a, long b) {
        return ((1L*a*b)/gcd(a, b));
    }
}

import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class A {
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        // Scanner scan = new Scanner(System.in);
        // PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(bf.readLine());
        StringTokenizer st = new StringTokenizer(bf.readLine());
        int[][] a = new int[n+1][n];
        for(int i=0; i<n; i++) a[0][i] = i+1;
        for(int i=0; i<n; i++) a[1][i] = Integer.parseInt(st.nextToken());
        int[] b = new int[n];
        for(int i=0; i<n; i++) {
            int counter = 1;
            int val = i;
            while(a[1][val]-1 != i) {
                counter++;
                val = a[1][val]-1;
                if(counter > 300) {
                    counter = Integer.MAX_VALUE;
                    break;
                }
            }
            b[i] = counter;
        }
        long[] ans = new long[n+1];
        Arrays.fill(ans, 1);
        for(int i=1; i<=n; i++)
            for(int j=0; j<n; j++)
                a[i][j] = a[1][a[i-1][j]-1];
        for(int i=1; i<=n; i++) {
            for(int j=0; j<n; j++) {
                //System.out.println(n + " " + i + " " + j + " " + a[i-1][j]);
                ans[i] = lcm(ans[i], b[a[i][j]-1]);
                if(ans[i] > 300) break;
            }
            if(i % ans[i] == 0) {
                System.out.println(i);
                System.exit(0);
            }
        }
        // int n = Integer.parseInt(st.nextToken());
        // int n = scan.nextInt();

        // out.close(); System.exit(0);
    }
    public static long gcd(long a, long b) {
        if(b == 0) return a;
        return gcd(b, a % b);
    }
    public static long lcm(long a, long b) {
        return ((1L*a*b)/gcd(a, b));
    }
}

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

public class VKr3qA {

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    PrintWriter w = new PrintWriter(System.out);

	    StringTokenizer st1 = new StringTokenizer(br.readLine());
	    int n = ip(st1.nextToken());

	    StringTokenizer st2 = new StringTokenizer(br.readLine());
	    int a[] = new int[n];
	    for(int i=0;i<n;i++)
	    	a[i] = ip(st2.nextToken()) - 1;

	    int f[] = new int[n];
	    for(int i=0;i<n;i++)
	    	f[i] = a[i];

	    int min[] = new int[n];
	    Arrays.fill(min,Integer.MAX_VALUE);

	    boolean done[] = new boolean[n];
	    int start[] = new int[n];

	    for(int k=1;k<=n*n;k++){

	    	for(int i=0;i<n;i++){
	    		if(f[i] == i && !done[i]){
	    			start[i] = k;
	    			done[i] = true;
	    			min[i] = 1;
	    		}
	    	}

	    	for(int i=0;i<n;i++){
	    		if(!done[i] && done[f[i]]){
	    			done[i] = true;
	    			start[i] = -1;
	    			min[i] = k;
	    		}
	    	}

	    	for(int i=0;i<n;i++)
	    		if(f[f[i]] == f[i])
	    			min[i] = Math.min(min[i],k);

	    	boolean yes = true;
	    	for(int i=0;i<n;i++)
	    		if(f[f[i]] != f[i])
	    			yes = false;

	    	if(yes){
	    		System.out.println(k);
	    		return;
	    	}

	    	for(int i=0;i<n;i++)
	    		f[i] = a[f[i]];
	  	}

	    for(int i=0;i<n;i++)
	    	if(min[i] == Integer.MAX_VALUE)
	    		throw new Exception("WA");

	    long ans = 1;
	    TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();

	    for(int i=0;i<n;i++){
	    	int num = min[i];
	    	for(int j=2;j<=5*n;j++){
	    		int count = 0;
	    		while(num % j == 0){
	    			count++;
	    			num /= j;
	    		}
	    		if(count > 0){
	    			if(map.containsKey(j))
	    				map.put(j, Math.max(map.get(j),count));
	    			else
	    				map.put(j,count);
	    		}
	    	}
	    }

	    Iterator<Integer> it = map.keySet().iterator();
	    while(it.hasNext()){
	    	int t = it.next();
	    	ans *= pow(t,map.get(t));
	    }

	    int max = 1;
	    for(int i=0;i<n;i++)
	    	max = Math.max(max, start[i]);

	    long ans2 = ans;
	    while(ans2 < max)
	    	ans2 += ans;
	    w.println(ans2);
	    w.close();
	}

	public static long pow(int a,int b){
		if(b == 0)
			return  1;
		if(b == 1)
			return a;
		long t = pow(a,b/2);
		if(b % 2 != 0)
			t *= a;
		return t;
	}

	public static int ip(String s){
		return Integer.parseInt(s);
	}

}

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

public class VKr3qA {

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    PrintWriter w = new PrintWriter(System.out);

	    StringTokenizer st1 = new StringTokenizer(br.readLine());
	    int n = ip(st1.nextToken());

	    StringTokenizer st2 = new StringTokenizer(br.readLine());
	    int a[] = new int[n];
	    for(int i=0;i<n;i++)
	    	a[i] = ip(st2.nextToken()) - 1;

	    int f[] = new int[n];
	    for(int i=0;i<n;i++)
	    	f[i] = a[i];

	    for(int k=1;k<=n*n + 1;k++){

	    	boolean yes = true;
	    	for(int i=0;i<n;i++)
	    		if(f[f[i]] != f[i])
	    			yes = false;

	    	if(yes){
	    		w.println(k);
	    		break;
	    	}

	    	for(int i=0;i<n;i++)
	    		f[i] = a[f[i]];

	    }

	    w.close();
	}

	public static int ip(String s){
		return Integer.parseInt(s);
	}

}

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

public class VKr3qA {

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    PrintWriter w = new PrintWriter(System.out);

	    StringTokenizer st1 = new StringTokenizer(br.readLine());
	    int n = ip(st1.nextToken());

	    StringTokenizer st2 = new StringTokenizer(br.readLine());
	    int a[] = new int[n];
	    for(int i=0;i<n;i++)
	    	a[i] = ip(st2.nextToken()) - 1;

	    int f[] = new int[n];
	    for(int i=0;i<n;i++)
	    	f[i] = a[i];

	    int min[] = new int[n];
	    Arrays.fill(min,Integer.MAX_VALUE);

	    boolean done[] = new boolean[n];
	    int start[] = new int[n];

	    for(int k=1;k<=n*n;k++){

	    	for(int i=0;i<n;i++){
	    		if(f[i] == i && !done[i]){
	    			start[i] = k;
	    			done[i] = true;
	    			min[i] = 1;
	    		}
	    	}

	    	for(int i=0;i<n;i++){
	    		if(!done[i] && done[f[i]]){
	    			done[i] = true;
	    			start[i] = -1;
	    			min[i] = k;
	    		}
	    	}

	    	boolean yes = true;
	    	for(int i=0;i<n;i++)
	    		if(f[f[i]] != f[i])
	    			yes = false;

	    	if(yes){
	    		System.out.println(k);
	    		return;
	    	}

	    	for(int i=0;i<n;i++)
	    		f[i] = a[f[i]];
	  	}

	    for(int i=0;i<n;i++)
	    	if(min[i] == Integer.MAX_VALUE)
	    		throw new Exception("WA");

	    long ans = 1;
	    TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();

	    for(int i=0;i<n;i++){
	    	int num = min[i];
	    	for(int j=2;j<=5*n;j++){
	    		int count = 0;
	    		while(num % j == 0){
	    			count++;
	    			num /= j;
	    		}
	    		if(count > 0){
	    			if(map.containsKey(j))
	    				map.put(j, Math.max(map.get(j),count));
	    			else
	    				map.put(j,count);
	    		}
	    	}
	    }

	    Iterator<Integer> it = map.keySet().iterator();
	    while(it.hasNext()){
	    	int t = it.next();
	    	ans *= pow(t,map.get(t));
	    }

	    int max = 1;
	    for(int i=0;i<n;i++)
	    	max = Math.max(max, start[i]);

	    long ans2 = ans;
	    while(ans2 < max)
	    	ans2 += ans;
	    w.println(ans2);
	    w.close();
	}

	public static long pow(int a,int b){
		if(b == 0)
			return  1;
		if(b == 1)
			return a;
		long t = pow(a,b/2);
		if(b % 2 != 0)
			t *= a;
		return t;
	}

	public static int ip(String s){
		return Integer.parseInt(s);
	}

}

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

public class VKr3qA {

	static int n;
	static int f[],distToCycle[];
	static boolean vis[],inCycle[],inStack[];
	static ArrayList<Integer> cycleLengths;

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    PrintWriter w = new PrintWriter(System.out);

	    n = ip(br.readLine());

	    StringTokenizer st2 = new StringTokenizer(br.readLine());
	    f = new int[n];
	    for(int i=0;i<n;i++)
	    	f[i] = ip(st2.nextToken()) - 1;

	    vis = new boolean[n];
	    inCycle = new boolean[n];
	    inStack = new boolean[n];
	    cycleLengths = new ArrayList<Integer>();

	    for(int i=0;i<n;i++){
	    	if(!vis[i]){
	    		vis[i] = true;
	    		dfs1(i);
	    	}
	    }

	    distToCycle = new int[n];
	    Arrays.fill(distToCycle, -1);
	    for(int i=0;i<n;i++)
	    	if(distToCycle[i] == -1)	dfs2(i);

	    long lcm = 1;
	    for(int x : cycleLengths)
	    	lcm = lcm(lcm,x);

	    long ans = lcm;
	    for(int i=0;i<n;i++)
	    	if(ans < distToCycle[i])
	    		ans += lcm;

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

	public static void dfs1(int curr){
		inStack[curr] = true;
		if(!vis[f[curr]]){
			vis[f[curr]] = true;
			dfs1(f[curr]);
		}
		else{
			if(!inCycle[f[curr]] && inStack[f[curr]]){
				int root = f[curr],cycleLength=1;
				inCycle[curr] = true;
				while(root != curr){
					inCycle[root] = true;
					cycleLength++;
					root = f[root];
				}
				cycleLengths.add(cycleLength);
			}
		}
		inStack[curr] = false;
	}

	public static int dfs2(int curr){
		if(distToCycle[curr] == -1){
			if(inCycle[curr])
				distToCycle[curr] = 0;
			else
				distToCycle[curr] = 1 + dfs2(f[curr]);
		}
		return distToCycle[curr];
	}

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

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

	public static int ip(String s){
		return Integer.parseInt(s);
	}

}

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

public class VKr3qA {

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    PrintWriter w = new PrintWriter(System.out);

	    StringTokenizer st1 = new StringTokenizer(br.readLine());
	    int n = ip(st1.nextToken());

	    StringTokenizer st2 = new StringTokenizer(br.readLine());
	    int a[] = new int[n];
	    for(int i=0;i<n;i++)
	    	a[i] = ip(st2.nextToken()) - 1;

	    int f[] = new int[n];
	    for(int i=0;i<n;i++)
	    	f[i] = a[i];

	    int min[] = new int[n];
	    Arrays.fill(min,Integer.MAX_VALUE);

	    for(int k=1;k<=600000;k++){

	    	for(int i=0;i<n;i++)
	    		if(f[f[i]] == f[i])
	    			min[i] = Math.min(min[i],k);

	    	boolean yes = true;
	    	for(int i=0;i<n;i++)
	    		if(f[f[i]] != f[i])
	    			yes = false;

	    	if(yes){
	    		System.out.println(k);
	    		return;
	    	}

	    	for(int i=0;i<n;i++)
	    		f[i] = a[f[i]];
	  	}

	    for(int i=0;i<n;i++)
	    	if(min[i] == Integer.MAX_VALUE)
	    		throw new Exception("WA");

	    long ans = 1;
	    TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();

	    for(int i=0;i<n;i++){
	    	int num = min[i];
	    	for(int j=2;j<=5*n;j++){
	    		int count = 0;
	    		while(num % j == 0){
	    			count++;
	    			num /= j;
	    		}
	    		if(count > 0){
	    			if(map.containsKey(j))
	    				map.put(j, Math.max(map.get(j),count));
	    			else
	    				map.put(j,count);
	    		}
	    	}
	    }

	    Iterator<Integer> it = map.keySet().iterator();
	    while(it.hasNext()){
	    	int t = it.next();
	    	ans *= pow(t,map.get(t));
	    }

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

	public static long pow(int a,int b){
		if(b == 0)
			return  1;
		if(b == 1)
			return a;
		long t = pow(a,b/2);
		if(b % 2 != 0)
			t *= a;
		return t;
	}

	public static int ip(String s){
		return Integer.parseInt(s);
	}

}

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

public class VKr3qA {

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    PrintWriter w = new PrintWriter(System.out);

	    StringTokenizer st1 = new StringTokenizer(br.readLine());
	    int n = ip(st1.nextToken());

	    StringTokenizer st2 = new StringTokenizer(br.readLine());
	    int a[] = new int[n];
	    for(int i=0;i<n;i++)
	    	a[i] = ip(st2.nextToken()) - 1;

	    int f[] = new int[n];
	    for(int i=0;i<n;i++)
	    	f[i] = a[i];

	    int min[] = new int[n];
	    Arrays.fill(min,Integer.MAX_VALUE);

	    for(int k=1;k<=5*n*n + 5*n;k++){

	    	for(int i=0;i<n;i++)
	    		if(f[f[i]] == f[i])
	    			min[i] = Math.min(min[i],k);

	    	boolean yes = true;
	    	for(int i=0;i<n;i++)
	    		if(f[f[i]] != f[i])
	    			yes = false;

	    	if(yes){
	    		System.out.println(k);
	    		return;
	    	}

	    	for(int i=0;i<n;i++)
	    		f[i] = a[f[i]];
	  	}

	    for(int i=0;i<n;i++)
	    	if(min[i] == Integer.MAX_VALUE)
	    		throw new Exception("WA");

	    long ans = 1;
	    TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();

	    for(int i=0;i<n;i++){
	    	int num = min[i];
	    	for(int j=2;j<=5*n;j++){
	    		int count = 0;
	    		while(num % j == 0){
	    			count++;
	    			num /= j;
	    		}
	    		if(count > 0){
	    			if(map.containsKey(j))
	    				map.put(j, Math.max(map.get(j),count));
	    			else
	    				map.put(j,count);
	    		}
	    	}
	    }

	    Iterator<Integer> it = map.keySet().iterator();
	    while(it.hasNext()){
	    	int t = it.next();
	    	ans *= pow(t,map.get(t));
	    }

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

	public static long pow(int a,int b){
		if(b == 0)
			return  1;
		if(b == 1)
			return a;
		long t = pow(a,b/2);
		if(b % 2 != 0)
			t *= a;
		return t;
	}

	public static int ip(String s){
		return Integer.parseInt(s);
	}

}

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

public class VKr3qA {

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    PrintWriter w = new PrintWriter(System.out);

	    StringTokenizer st1 = new StringTokenizer(br.readLine());
	    int n = ip(st1.nextToken());

	    StringTokenizer st2 = new StringTokenizer(br.readLine());
	    int a[] = new int[n];
	    for(int i=0;i<n;i++)
	    	a[i] = ip(st2.nextToken()) - 1;

	    int f[] = new int[n];
	    for(int i=0;i<n;i++)
	    	f[i] = a[i];

	    int min[] = new int[n];
	    Arrays.fill(min,Integer.MAX_VALUE);

	    for(int k=1;k<=5*n*n + n;k++){

	    	for(int i=0;i<n;i++)
	    		if(f[f[i]] == f[i])
	    			min[i] = Math.min(min[i],k);

	    	for(int i=0;i<n;i++)
	    		f[i] = a[f[i]];
	  	}

	    for(int i=0;i<n;i++)
	    	if(min[i] == Integer.MAX_VALUE)
	    		throw new Exception("WA");

	    long ans = 1;
	    TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();

	    for(int i=0;i<n;i++){
	    	int num = min[i];
	    	for(int j=2;j<=5*n;j++){
	    		int count = 0;
	    		while(num % j == 0){
	    			count++;
	    			num /= j;
	    		}
	    		if(count > 0){
	    			if(map.containsKey(j))
	    				map.put(j, Math.max(map.get(j),count));
	    			else
	    				map.put(j,count);
	    		}
	    	}
	    }

	    Iterator<Integer> it = map.keySet().iterator();
	    while(it.hasNext()){
	    	int t = it.next();
	    	ans *= pow(t,map.get(t));
	    }

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

	public static long pow(int a,int b){
		if(b == 0)
			return  1;
		if(b == 1)
			return a;
		long t = pow(a,b/2);
		if(b % 2 != 0)
			t *= a;
		return t;
	}

	public static int ip(String s){
		return Integer.parseInt(s);
	}

}

import java.util.*;
public class c {
public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    int[] f = new int[n+1];
    for(int i = 1; i<=n; i++) f[i] = input.nextInt();
    int[] g = new int[n+1];
    for(int i = 0; i<=n; i++) g[i] = f[i];
    int res = 1;
    int[] cycles = new int[n+1];
    int[] off = new int[n+1];
    for(int i = 1; i<=n; i++)
    {
        cycles[i] = 0;
        int at = i;
        int[] last = new int[n+1];
        Arrays.fill(last, -1);
        int ctr = 0;
        last[i] = 0;
        while(true)
        {
            at = f[at];
            ctr++;
            if(last[at] != -1)
            {
                off[i] = last[at];
                cycles[i] = ctr - last[at];
                break;
            }
            last[at] = ctr;
        }
    }
    //System.out.println(Arrays.toString(cycles)+" "+Arrays.toString(off));
    long lcm = 1;
    for(int i = 1; i<=n; i++)
    {
        lcm = lcm(lcm, cycles[i]);
    }
    for(int i = 1; i<=n; i++) lcm = Math.max(lcm, off[i]);
    System.out.println(lcm);
//  while(true)
//  {
//      boolean valid = true;
//      for(int i = 1; i<=n; i++) if(g[g[i]] != g[i])
//      {
//          valid = false;
//          break;
//      }
//      if(valid)
//      {
//          System.out.println(res);
//          break;
//      }
//      res++;
//      for(int i = 1; i<=n; i++) g[i] = f[g[i]];
//  }
}
static long gcd(long a, long b)
{
    return b == 0 ? a : gcd(b, a%b);
}
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.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class C {
	static InputStreamReader isr = new InputStreamReader(System.in);
	static BufferedReader br = new BufferedReader(isr);

	static int[] readIntArray() throws IOException {
		String[] v = br.readLine().split(" ");
		int[] ans = new int[v.length];

		for (int i = 0; i < ans.length; i++) {
			ans[i] = Integer.valueOf(v[i]);
		}

		return ans;
	}

	static int[] vals;

	static int[] next(int[] c) {
		int[] ans = new int[c.length];
		for (int i = 0; i < ans.length; i++) {
			ans[i] = vals[c[i]];
		}

		return ans;
	}

	public static void main(String[] args) throws IOException {
		int[] l = readIntArray();
		vals = readIntArray();

		// Random r = new Random();
		// vals = new int[5];
		// for (int i = 0; i < vals.length; i++) {
		// vals[i] = r.nextInt(vals.length) + 1;
		// }

		for (int i = 0; i < vals.length; i++) {
			vals[i]--;
		}

		int[] nums = new int[vals.length];
		int[] adds = new int[vals.length];
		for (int i = 0; i < vals.length; i++) {
			int s1 = i;
			int s2 = s1;
			int s3 = s2;
			List<Integer> le = new ArrayList<Integer>();
			for (int j = 1; j < 5000; j++) {
				for (int j2 = 0; j2 < 1; j2++) {
					s2 = vals[s2];
				}
				for (int j2 = 0; j2 < 2; j2++) {
					s3 = vals[s3];
				}

				if (s2 == s3) {
					le.add(j);
					// if (i == 5)
					// System.out.println(i + " : " + j);
				}
			}

			nums[i] = le.get(0);
			adds[i] = le.get(1) - le.get(0);
		}

		long ans = nums[0];
		long step = adds[0];
		for (int i = 1; i < nums.length; i++) {
			while (true) {
				if (((ans - nums[i]) % adds[i]) != 0) {
					ans += step;
				} else {
					break;
				}
			}

			step = lcm(step, adds[i]);
		}

		// System.out.println(Arrays.toString(nums));
		// System.out.println(Arrays.toString(adds));
		System.out.println(ans);
	}

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

	static long gcd(long a, long b) {
		if (a < b)
			return gcd(b, a);

		while (b != 0) {
			long t = b;
			b = a % b;
			a = t;
		}

		return a;
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class C {
	static InputStreamReader isr = new InputStreamReader(System.in);
	static BufferedReader br = new BufferedReader(isr);

	static int[] readIntArray() throws IOException {
		String[] v = br.readLine().split(" ");
		int[] ans = new int[v.length];

		for (int i = 0; i < ans.length; i++) {
			ans[i] = Integer.valueOf(v[i]);
		}

		return ans;
	}

	static int[] vals;

	static int[] next(int[] c) {
		int[] ans = new int[c.length];
		for (int i = 0; i < ans.length; i++) {
			ans[i] = vals[c[i]];
		}

		return ans;
	}

	public static void main(String[] args) throws IOException {
		int[] l = readIntArray();
		vals = readIntArray();

		// Random r = new Random();
		// vals = new int[5];
		// for (int i = 0; i < vals.length; i++) {
		// vals[i] = r.nextInt(vals.length) + 1;
		// }

		for (int i = 0; i < vals.length; i++) {
			vals[i]--;
		}

		int[] nums = new int[vals.length];
		int[] adds = new int[vals.length];
		for (int i = 0; i < vals.length; i++) {
			int s1 = i;
			int s2 = s1;
			int s3 = s2;
			List<Integer> le = new ArrayList<Integer>();
			for (int j = 1; j < 400; j++) {
				for (int j2 = 0; j2 < 1; j2++) {
					s2 = vals[s2];
				}
				for (int j2 = 0; j2 < 2; j2++) {
					s3 = vals[s3];
				}

				if (s2 == s3) {
					le.add(j);
//					if (i == 5)
//						System.out.println(i + " : " + j);
				}
			}

			nums[i] = le.get(0);
			adds[i] = le.get(1) - le.get(0);
		}

		// long ans = 1;
		for (int i = 1; i < 100000; i++) {
			boolean ok = true;
			for (int j = 0; j < nums.length; j++) {
				if (i < nums[j] || ((i - nums[j]) % adds[j]) != 0) {
					ok = false;
					break;
				}
			}

			if (ok) {
				System.out.println(i);
				return;
			}
		}

		// System.out.println(Arrays.toString(vals));
		// System.out.println(Arrays.toString(nums));
		// System.out.println(ans);
	}

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

	static long gcd(long a, long b) {
		if (a < b)
			return gcd(b, a);

		while (b != 0) {
			long t = b;
			b = a % b;
			a = t;
		}

		return a;
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;

public class C {
	static InputStreamReader isr = new InputStreamReader(System.in);
	static BufferedReader br = new BufferedReader(isr);

	static int[] readIntArray() throws IOException {
		String[] v = br.readLine().split(" ");
		int[] ans = new int[v.length];

		for (int i = 0; i < ans.length; i++) {
			ans[i] = Integer.valueOf(v[i]);
		}

		return ans;
	}

	static int[] vals;

	static int[] next(int[] c) {
		int[] ans = new int[c.length];
		for (int i = 0; i < ans.length; i++) {
			ans[i] = vals[c[i]];
		}

		return ans;
	}

	public static void main(String[] args) throws IOException {
		int[] l = readIntArray();
		vals = readIntArray();

//		Random r = new Random();
//		vals = new int[5];
//		for (int i = 0; i < vals.length; i++) {
//			vals[i] = r.nextInt(vals.length) + 1;
//		}

		for (int i = 0; i < vals.length; i++) {
			vals[i]--;
		}

		int[] nums = new int[vals.length];
		for (int i = 0; i < vals.length; i++) {
			int s1 = i;
			int s2 = s1;
			int s3 = s2;
			for (int j = 1; j < 100000; j++) {
				for (int j2 = 0; j2 < 1; j2++) {
					s2 = vals[s2];
				}
				for (int j2 = 0; j2 < 2; j2++) {
					s3 = vals[s3];
				}

				if (s2 == s3) {
					nums[i] = j;
					break;
				}
			}
		}

		long ans = 1;
		for (int i = 0; i < nums.length; i++) {
			ans = lcm(ans, nums[i]);
		}

//		System.out.println(Arrays.toString(vals));
//		System.out.println(Arrays.toString(nums));
		System.out.println(ans);
	}

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

		while(b != 0) {
			long t = b;
			b = a % b;
			a = t;
		}

		return a;
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class C {
	static InputStreamReader isr = new InputStreamReader(System.in);
	static BufferedReader br = new BufferedReader(isr);

	static int[] readIntArray() throws IOException {
		String[] v = br.readLine().split(" ");
		int[] ans = new int[v.length];

		for (int i = 0; i < ans.length; i++) {
			ans[i] = Integer.valueOf(v[i]);
		}

		return ans;
	}

	static int[] vals;

	static int[] next(int[] c) {
		int[] ans = new int[c.length];
		for (int i = 0; i < ans.length; i++) {
			ans[i] = vals[c[i]];
		}

		return ans;
	}

	public static void main(String[] args) throws IOException {
		int[] l = readIntArray();
		vals = readIntArray();

		// Random r = new Random();
		// vals = new int[5];
		// for (int i = 0; i < vals.length; i++) {
		// vals[i] = r.nextInt(vals.length) + 1;
		// }

		for (int i = 0; i < vals.length; i++) {
			vals[i]--;
		}

		int[] nums = new int[vals.length];
		int[] adds = new int[vals.length];
		for (int i = 0; i < vals.length; i++) {
			int s1 = i;
			int s2 = s1;
			int s3 = s2;
			List<Integer> le = new ArrayList<Integer>();
			for (int j = 1; j < 500; j++) {
				for (int j2 = 0; j2 < 1; j2++) {
					s2 = vals[s2];
				}
				for (int j2 = 0; j2 < 2; j2++) {
					s3 = vals[s3];
				}

				if (s2 == s3) {
					le.add(j);
//					if (i == 5)
//						System.out.println(i + " : " + j);
				}
			}

			nums[i] = le.get(0);
			adds[i] = le.get(1) - le.get(0);
		}

		int ma = 0;
		for (int i = 1; i < adds.length; i++) {
			if (adds[i] > adds[ma]) {
				ma = i;
			}
		}
		// long ans = 1;
		for (int i = nums[ma]; i <= 1000000000; i += adds[ma]) {
			boolean ok = true;
			for (int j = 0; j < nums.length; j++) {
				if (i < nums[j] || ((i - nums[j]) % adds[j]) != 0) {
					ok = false;
					break;
				}
			}

			if (ok) {
				System.out.println(i);
				return;
			}
		}

		 System.out.println(Arrays.toString(nums));
		 System.out.println(Arrays.toString(adds));
		// System.out.println(ans);
	}

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

	static long gcd(long a, long b) {
		if (a < b)
			return gcd(b, a);

		while (b != 0) {
			long t = b;
			b = a % b;
			a = t;
		}

		return a;
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class C {
	static InputStreamReader isr = new InputStreamReader(System.in);
	static BufferedReader br = new BufferedReader(isr);

	static int[] readIntArray() throws IOException {
		String[] v = br.readLine().split(" ");
		int[] ans = new int[v.length];

		for (int i = 0; i < ans.length; i++) {
			ans[i] = Integer.valueOf(v[i]);
		}

		return ans;
	}

	static int[] vals;

	static int[] next(int[] c) {
		int[] ans = new int[c.length];
		for (int i = 0; i < ans.length; i++) {
			ans[i] = vals[c[i]];
		}

		return ans;
	}

	public static void main(String[] args) throws IOException {
		int[] l = readIntArray();
		vals = readIntArray();

		// Random r = new Random();
		// vals = new int[5];
		// for (int i = 0; i < vals.length; i++) {
		// vals[i] = r.nextInt(vals.length) + 1;
		// }

		for (int i = 0; i < vals.length; i++) {
			vals[i]--;
		}

		int[] nums = new int[vals.length];
		int[] adds = new int[vals.length];
		for (int i = 0; i < vals.length; i++) {
			int s1 = i;
			int s2 = s1;
			int s3 = s2;
			List<Integer> le = new ArrayList<Integer>();
			for (int j = 1; j < 500; j++) {
				for (int j2 = 0; j2 < 1; j2++) {
					s2 = vals[s2];
				}
				for (int j2 = 0; j2 < 2; j2++) {
					s3 = vals[s3];
				}

				if (s2 == s3) {
					le.add(j);
					// if (i == 5)
					// System.out.println(i + " : " + j);
				}
			}

			nums[i] = le.get(0);
			adds[i] = le.get(1) - le.get(0);
		}

		int ma = 0;
		for (int i = 1; i < adds.length; i++) {
			if (adds[i] > adds[ma]) {
				ma = i;
			}
		}

		long ans = nums[0];
		long step = adds[0];
		for (int i = 1; i < nums.length; i++) {
			while (true) {
				if (((ans - nums[i]) % adds[i]) != 0) {
					ans += step;
				} else {
					break;
				}
			}

			step = lcm(step, adds[i]);
		}

		// System.out.println(Arrays.toString(nums));
		// System.out.println(Arrays.toString(adds));
		System.out.println(ans);
	}

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

	static long gcd(long a, long b) {
		if (a < b)
			return gcd(b, a);

		while (b != 0) {
			long t = b;
			b = a % b;
			a = t;
		}

		return a;
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;

public class C {
	static InputStreamReader isr = new InputStreamReader(System.in);
	static BufferedReader br = new BufferedReader(isr);

	static int[] readIntArray() throws IOException {
		String[] v = br.readLine().split(" ");
		int[] ans = new int[v.length];

		for (int i = 0; i < ans.length; i++) {
			ans[i] = Integer.valueOf(v[i]);
		}

		return ans;
	}

	static int[] vals;

	static int[] next(int[] c) {
		int[] ans = new int[c.length];
		for (int i = 0; i < ans.length; i++) {
			ans[i] = vals[c[i]];
		}

		return ans;
	}

	public static void main(String[] args) throws IOException {
		int[] l = readIntArray();
		vals = readIntArray();

//		Random r = new Random();
//		vals = new int[5];
//		for (int i = 0; i < vals.length; i++) {
//			vals[i] = r.nextInt(vals.length) + 1;
//		}

		for (int i = 0; i < vals.length; i++) {
			vals[i]--;
		}

		int[] nums = new int[vals.length];
		for (int i = 0; i < vals.length; i++) {
			for (int j = 1; j < 210; j++) {
				int s1 = i;
				int s2 = s1;
				for (int j2 = 0; j2 < j; j2++) {
					s2 = vals[s2];
				}
				int s3 = s2;
				for (int j2 = 0; j2 < j; j2++) {
					s3 = vals[s3];
				}

				if (s2 == s3) {
					nums[i] = j;
					break;
				}
			}
		}

		long ans = 1;
		for (int i = 0; i < nums.length; i++) {
			ans = lcm(ans, nums[i]);
		}

//		System.out.println(Arrays.toString(vals));
//		System.out.println(Arrays.toString(nums));
		System.out.println(ans);
	}

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

		while(b != 0) {
			long t = b;
			b = a % b;
			a = t;
		}

		return a;
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class C {
	static InputStreamReader isr = new InputStreamReader(System.in);
	static BufferedReader br = new BufferedReader(isr);

	static int[] readIntArray() throws IOException {
		String[] v = br.readLine().split(" ");
		int[] ans = new int[v.length];

		for (int i = 0; i < ans.length; i++) {
			ans[i] = Integer.valueOf(v[i]);
		}

		return ans;
	}

	static int[] vals;

	public static void main(String[] args) throws IOException {
		int[] l = readIntArray();
		vals = readIntArray();
		for (int i = 0; i < vals.length; i++) {
			vals[i]--;
		}

		int[] nums = new int[vals.length];
		for (int i = 0; i < vals.length; i++) {
			boolean[] visited = new boolean[vals.length];
			visited[i] = true;
			int a = i;
			int steps = 0;
			while(true) {
				if (vals[a] == a) {
					break;
				}

				if (visited[vals[a]]) {
					steps++;
					break;
				}

				a = vals[a];
				visited[a] = true;
				steps++;
			}

			nums[i] = Math.max(steps, 1);
		}

		long ans = 1;
		for (int i = 0; i < nums.length; i++) {
			ans = lcm(ans, nums[i]);
		}

		System.out.println(Arrays.toString(nums));
		System.out.println(ans);
	}

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

		while(b != 0) {
			long t = b;
			b = a % b;
			a = t;
		}

		return a;
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class C {
	static InputStreamReader isr = new InputStreamReader(System.in);
	static BufferedReader br = new BufferedReader(isr);

	static int[] readIntArray() throws IOException {
		String[] v = br.readLine().split(" ");
		int[] ans = new int[v.length];

		for (int i = 0; i < ans.length; i++) {
			ans[i] = Integer.valueOf(v[i]);
		}

		return ans;
	}

	static int[] vals;

	public static void main(String[] args) throws IOException {
		int[] l = readIntArray();
		vals = readIntArray();
		for (int i = 0; i < vals.length; i++) {
			vals[i]--;
		}

		int[] nums = new int[vals.length];
		for (int i = 0; i < vals.length; i++) {
			boolean[] visited = new boolean[vals.length];
			visited[i] = true;
			int a = i;
			int steps = 0;
			while(true) {
				if (vals[a] == a) {
					break;
				}

				if (visited[vals[a]]) {
					steps++;
					break;
				}

				a = vals[a];
				visited[a] = true;
				steps++;
			}

			nums[i] = Math.max(steps, 1);
		}

		long ans = 1;
		for (int i = 0; i < nums.length; i++) {
			ans = lcm(ans, nums[i]);
		}

//		System.out.println(Arrays.toString(nums));
		System.out.println(ans);
	}

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

		while(b != 0) {
			long t = b;
			b = a % b;
			a = t;
		}

		return a;
	}
}