Advertisement
Guest User

Combination.java

a guest
Oct 6th, 2012
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1.  
  2. import java.util.HashMap;
  3. import java.util.Map;
  4.  
  5. public class Combination {
  6.    
  7.     private Map<Integer,Long> factorialMap = new HashMap<Integer,Long>();
  8.    
  9.     public Long getFactorial(int number) {
  10.         Long val = factorialMap.get(number);
  11.         if(val != null) {
  12.             return val;
  13.         } else {
  14.             val = getFactorialRecursive(number);
  15.             factorialMap.put(number, val);
  16.             return val;
  17.         }
  18.     }
  19.    
  20.     public Long getFactorialRecursive(int number) {
  21.         if(number == 1 || number == 0) {
  22.             return 1L;
  23.         } else {
  24.             return number * getFactorialRecursive(number-1);
  25.         }
  26.     }
  27.    
  28.     public Long combination(int fromVal, int chooseVal) {
  29.         return getFactorial(fromVal)/(getFactorial(chooseVal)*getFactorial(fromVal-chooseVal));
  30.     }
  31.    
  32.    
  33.     public static void main(String[] args) {
  34.         Combination comb = new Combination();
  35.         for(int i = 0; i < 20; i++) {
  36.             System.out.print(20 +" chose " + i + " = ");
  37.             System.out.println(comb.combination(20,i));
  38.         }
  39.                
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement