Java Program to Perform nCr (rcombinations)


In this article, we will understand how to compute the combination using n and r values. The nCr is calculated using the formula −

(factorial of n) / (factorial of (n-r))

Below is a demonstration of the same −

Input

Suppose our input is −

Value of n : 6
Value of r : 4

Output

The desired output would be −

The nCr value is : 15

Algorithm

Step 1 - START
Step 2 - Declare two integer values namely n and r.
Step 3 - Read the required values from the user/ define the values
Step 4 - Define two functions, one function to calculate the factorial of n and (n-r) and other
to compute the formula : (factorial of n) / (factorial of (n-r)) and store the result.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool run button.

import java.util.*;
public class Combination {
   static int Compute_nCr(int n, int r){
      return my_factorial(n) / (my_factorial(r) *
      my_factorial(n - r));
   }
   static int my_factorial(int n){
      int i, my_result;
      my_result = 1;
      for (i = 2; i <= n; i++)
         my_result = my_result * i;
      return my_result;
   }
   public static void main(String[] args){
      int n,r;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the value of n : ");
      n = my_scanner.nextInt();
      System.out.print("Enter the value of r : ");
      r = my_scanner.nextInt();
      System.out.println("The combination value for the given input is = "+Compute_nCr(n, r));
   }
}

Output

Required packages have been imported
A reader object has been defined
Enter the value of n : 6
Enter the value of r : 4
The combination value for the given input is = 15

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

public class Combination {
   static int Compute_nCr(int n, int r){
      return my_factorial(n) / (my_factorial(r) *
      my_factorial(n - r));
   }
   static int my_factorial(int n){
      int i, my_result;
      my_result = 1;
      for (i = 2; i <= n; i++)
         my_result = my_result * i;
      return my_result;
   }
   public static void main(String[] args){
      int n,r;
      n = 6 ;
      r = 4 ;
      System.out.println("The n and r values are defined as " +n + " and " +r);
      System.out.println("The combination value for the given input is = "+Compute_nCr(n, r));
   }
}

Output

The n and r values are defined as 6 and 4
The combination value for the given input is = 15

Updated on: 22-Feb-2022

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements