Advertisement
dimipan80

Calculate N! / (K! * (N-K)!)

Aug 8th, 2014
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.69 KB | None | 0 0
  1. /* In combinatorics, the number of ways to choose k different members out of a group
  2.  * of n different elements (also known as the number of combinations)
  3.  * is calculated by the following formula: result = (n! / (k! * (n - k)!)).
  4.  * For example, there are 2598960 ways to withdraw 5 cards out of a standard deck of 52 cards.
  5.  * Your task is to write a program that calculates n! / (k! * (n-k)!)
  6.  * for given n and k (1 < k < n < 100). Try to use only two loops. */
  7.  
  8. import java.math.BigInteger;
  9. import java.util.Locale;
  10. import java.util.Scanner;
  11.  
  12. public class _07_CalculateTheNumberOfCombinationsN_K {
  13.  
  14.     public static void main(String[] args) {
  15.         // TODO Auto-generated method stub
  16.         Locale.setDefault(Locale.ROOT);
  17.         Scanner scanner = new Scanner(System.in);
  18.         System.out.print("Enter a whole positive number in the range [3 .. 99] for N: ");
  19.         int numN = scanner.nextInt();
  20.         System.out.print("Enter other whole positive number in the range [2 .. N-1] for K: ");
  21.         int numK = scanner.nextInt();
  22.         scanner.close();
  23.  
  24.         if (numN < 100 && numN > numK && numK > 1) {
  25.             BigInteger factorialsDivisionNK = BigInteger.ONE;
  26.             for (int i = numN; i > numK; i--) {
  27.                 BigInteger numBig = new BigInteger("" + i);
  28.                 factorialsDivisionNK = factorialsDivisionNK.multiply(numBig);
  29.             }
  30.  
  31.             BigInteger factorialNminusK = BigInteger.ONE;
  32.             for (int i = numN - numK; i > 0; i--) {
  33.                 BigInteger numBig = new BigInteger("" + i);
  34.                 factorialNminusK = factorialNminusK.multiply(numBig);
  35.             }
  36.  
  37.             BigInteger result = factorialsDivisionNK.divide(factorialNminusK);
  38.  
  39.             System.out.println("The Number of Combinations is: " + result);
  40.         } else {
  41.             System.out.println("Error! - Invalid Input!!!");
  42.         }
  43.     }
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement