Advertisement
nate23nate23

hw 11

Oct 16th, 2015
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. import java.math.BigInteger;
  2. import java.util.Scanner;
  3.  
  4. /**
  5.  * Nate Wheeler
  6.  * compsci 220
  7.  * Hw 11
  8.  * nrwheeler@student.stcc.edu
  9.  *
  10.  */
  11. public class Combinations {
  12.  
  13.     public static BigInteger getNumberOfCombinations(int n, int k) {
  14.         BigInteger nfact = BigInteger.ONE;
  15.         BigInteger kfact = BigInteger.ONE;
  16.         int h = n - k;
  17.         BigInteger hfact = BigInteger.ONE;
  18.         // factorial of n
  19.         for (int i = 1; i <= n; i++)
  20.             nfact = nfact.multiply(BigInteger.valueOf((long) i));
  21.         // factorial of k
  22.         for (int i = 1; i <= k; i++)
  23.             kfact = kfact.multiply(BigInteger.valueOf((long) i));
  24.         // factorial of the difference between n and k
  25.         for (int i = 1; i <= h; i++)
  26.             hfact = hfact.multiply(BigInteger.valueOf((long) i));
  27.         // basic arithmetic
  28.         BigInteger combin = kfact.multiply(hfact);
  29.         combin = nfact.divide(combin);
  30.         // number of combinations
  31.         return combin;
  32.     }
  33.  
  34.     public static void main(String[] args) {
  35.         System.out.println("Enter n: ");
  36.         Scanner ncom = new Scanner(System.in);
  37.         System.out.println("Enter k: ");
  38.         Scanner kcom = new Scanner(System.in);
  39.         int n = ncom.nextInt();
  40.         int k = kcom.nextInt();
  41.         System.out.println("The C(n, k) is " + getNumberOfCombinations(n, k));
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement