//--------------------------------------------------------------------------- // Miranda Moore // COS488/MAT474 // Problem Set 9, Q2 //--------------------------------------------------------------------------- // The command "java Permutation N" // returns the number of permutations of N atoms that have no 1- or 2-cycles. // // Examples: // > java Permutation 3 // 2 // > java Permutation 4 // 6 // > java Permutation 5 // 24 // > java Permutation 6 // 160 //--------------------------------------------------------------------------- public class Permutation { // Counts the number of pemutations of N atoms having no 1- or 2-cycles private static long count(int N, long[] fact) { long count = 0; if (N == 0) count = 1; // necessary base case else if (N == 1 || N == 2) count = 0; else { // All the possibilities for a cycle of size >= 3 // containing the atom of largest index for (int k = 2; k <= N-1; k++) { count += (fact[N-1]/fact[N-k-1] * count(N-k-1, fact)); } } return count; } public static void main(String[] args) { int N = Integer.parseInt(args[0]); // Compute array of all the factorials long[] fact = new long[N+1]; fact[0] = 1; for (int i = 1; i <= N; i++) { fact[i] = i*fact[i-1]; } System.out.println(count(N, fact)); } }