import java.util.Scanner; public class SpockFast { /** * Recursive computation of n choose k * @param n >= 0 * @param k <= n * @return the number of possible combinations of * k out of n */ public int combRec(int n, int k){ // pre: 0 <= k <= n // n < 0 // post: return the number of possible combinations of // k out of n if (n==k || k==0) return 1; else // n>k and k>0 return combRec(n-1,k-1) + combRec(n-1,k); } /* * Fast Spock */ public long combFast(int n, int k, long[][] A) { // pre: 0 <= k <= n // n < 0 // post: return the number of possible combinations of // k out of n if (A[n][k] > 0) return A[n][k]; else if (n==k || k==0) return 1; else { A[n][k] = combFast(n-1,k-1, A) + combFast(n-1,k, A); return A[n][k]; } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner Input = new Scanner(System.in); int n; long start, finish, res; SpockFast S = new SpockFast(); do{ System.out.println("Enter set size n>0 (0 to finish)"); n = Input.nextInt(); long A[][] = new long[n+1][n+1]; if(n>0 && n<=33) { for(int k = 0; k<=n; k++){ start = System.currentTimeMillis(); res = S.combRec(n, k); finish = System.currentTimeMillis(); System.out.println("Number of combinations (slow): (" + n + " choose " +k+ ") = " + res + ", time = " + (finish-start) + " milliseconds"); start = System.currentTimeMillis(); res = S.combFast(n, k, A); finish = System.currentTimeMillis(); System.out.println("Number of combinations (fast): (" + n + " choose " +k+ ") = " + res + " time = " + (finish-start) + " milliseconds\n"); } } if (n > 33) System.out.println ("n > 33 will cause overflow"); } while (n>0); System.out.println("goodbye Spock"); } }