Latest :

Java Program To Find nCr & nPr | 5 Ways

Java program to find nCr and nPr. Here, we will discuss the various methods to permutations and combinations using Java. The compiler has been added so that you can execute the programs yourself, alongside suitable examples and sample outputs. The methods discussed are:

Permutation: is the process of arrangement of all the members in any set into a particular sequence or order.

For example, set A with members 1 & 2 can be arranged into 2 ways such as {1,2,} and {2,1}.

Combination: is the process of selection of members from any particular set.

For example, if we had to select 2 members at random from set A with members 1, 2 & 3, we’d have 3 possibilities namely {1,2}, {2,3} and {1,3}.

nCr & nPr – Using Function

1) In this program we have fact, permutation, combination functions to calculate ncr and npr.

2) Read n,r values using scanner object sc.nextInt(), and store it int the variables n,r.

p.permutation(n,r) then it calls the permutation method and permutation method calls the fact method and prints the permutation.

p.combination(n,r) then calls the combination method and combination method calls the fact method and prints the combination.

3) Repeats until the condition if(n>=r) is false.

Output:

Using Static Method

1) JVM runs the static block then static method then it creates an object for the class.

2) In this program, static double ncr(int n,int r), static double npr(int n,int r), public static void main(String arg[]). These 3 static methods are available.

3) Calls the two static methods ncr(),npr() in main method. The methods ncr(),npr() calls the fact() method using NcrAndNpr class object.

Output:

Using For Loop

1) Read the n,r values using scanner object sc.nextInt() and store it in the variables n,r.

2) We will calculate combination using this formula com=a.fact(n)/(a.fact(n-r)*a.fact(r));

3) Permutation using this formula per=a.fact(n)/a.fact(n-r); until n>=r is false.

4) The fact method will  calculate the factorial of a number using for loop. For loop iterates from i=0 to i=n, for each iteration f=f*i will be calculated and the result will be returned.

Output:

Using Recursion

In case if you have no idea what is recursion, then do check out the complete Guide here.

1) In this program factorial(double n) call itself as factorial(n-1), it returns 1 if n=0 otherwise it returns (n *factorial(n-1))

2) We will calculate combination using this formula com=a.factorial(n)/(a.factorial(n-r)*a.factorial(r)); and permutation using this formula per=a.factorial(n)/a.factorial(n-r); until n>=r is false.

Output:

x

Check Also

Java Inverted Mirrored Right Triangle Star Pattern

Java program to print Inverted mirrored right triangle star pattern program. We have written below ...