Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* In combinatorics, the number of ways to choose k different members out of a group
- * of n different elements (also known as the number of combinations)
- * is calculated by the following formula: result = (n! / (k! * (n - k)!)).
- * For example, there are 2598960 ways to withdraw 5 cards out of a standard deck of 52 cards.
- * Your task is to write a program that calculates n! / (k! * (n-k)!)
- * for given n and k (1 < k < n < 100). Try to use only two loops. */
- import java.math.BigInteger;
- import java.util.Locale;
- import java.util.Scanner;
- public class _07_CalculateTheNumberOfCombinationsN_K {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Locale.setDefault(Locale.ROOT);
- Scanner scanner = new Scanner(System.in);
- System.out.print("Enter a whole positive number in the range [3 .. 99] for N: ");
- int numN = scanner.nextInt();
- System.out.print("Enter other whole positive number in the range [2 .. N-1] for K: ");
- int numK = scanner.nextInt();
- scanner.close();
- if (numN < 100 && numN > numK && numK > 1) {
- BigInteger factorialsDivisionNK = BigInteger.ONE;
- for (int i = numN; i > numK; i--) {
- BigInteger numBig = new BigInteger("" + i);
- factorialsDivisionNK = factorialsDivisionNK.multiply(numBig);
- }
- BigInteger factorialNminusK = BigInteger.ONE;
- for (int i = numN - numK; i > 0; i--) {
- BigInteger numBig = new BigInteger("" + i);
- factorialNminusK = factorialNminusK.multiply(numBig);
- }
- BigInteger result = factorialsDivisionNK.divide(factorialNminusK);
- System.out.println("The Number of Combinations is: " + result);
- } else {
- System.out.println("Error! - Invalid Input!!!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement