Find Number of Combinations in Java

Finding no. of Combinations in Java
This lets you find no. of combinations in java using the standard nCr forumla. This is a simple logic.

The formula of nCr is n!/(n-r)!r!






import java.util.*;
class FindCombination
{
    public static void main(String args[])
    {
    Scanner s=new Scanner(System.in);

    System.out.println("Enter the value of n");
    int n=s.nextInt();
   
   
    System.out.println("Enter the combination suffix (r)");
    int r=s.nextInt();

    long res=1;

        if(n>=r)
        {
            res=getFact(n)/(getFact(n-r)*getFact(r));
            System.out.println("The result is "+res);
        }
        else System.out.println("r cannot be greater than n");
   
    }

    public static long getFact(int n)
    {
        long f=1;

        for(int i=n;i>=1;i--)
        {
        f*=i;
        }

    return f;
    }
}

Sample Output


Enter the value of n
7
Enter the combination suffix (r)
2
The result is 21

Analysis

n>=r: n cannot be greater than the suffix r in a combination.
getFact(n)/(getFact(n-r)*getFact(r)): This is the formula n!/((n-r)!.r!).
getFact() method has been explained in finding the factorial of a number in Java post.

Also see Permuting a number in Java using formula
This is the way in which we can calculate the number of combinations nCr is calculated provided the value of n and r.


Posted by at on

Tags: Playing with Numbers,