Program To Find nCr & nPr

(141 Views)


In this article, we will learn how to find nCr and nPr using Java program.

What is Permutation?

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

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

What is Combination?

Combination is the process of selecting members from any particular set.

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

Java Program to Find nCr and nPr

import java.util.Scanner; class NcrAndNpr { double combination(int n,int r) { double com=fact(n)/(fact(n-r)*fact(r)); return com; } // double permutation(int n,int r ) { double per=fact(n)/fact(n-r); return per; } // fact method is used to calculate factorial of number double fact(double n) { int i=1; double fact=1; while(i<=n) { fact=fact*i; i++; } return fact; } public static void main(String arg[]) { NcrAndNpr p=new NcrAndNpr(); Scanner sc=new Scanner(System.in); System.out.println("enter value of n"); int n=sc.nextInt(); System.out.println("enter value of r"); int r=sc.nextInt(); if(n>=r) { // p.permutation(n,r) calls the permutation method which internally calls the fact method and prints the permutation. System.out.println("The value of "+n+"p"+r+" is : "+p.permutation(n,r)); // p.combination(n,r) calls the combination method which internally calls the fact method and prints the combination. System.out.println("The value of "+n+"c"+r+" is : "+p.combination(n,r)); } else System.out.println("n value should be greater than or equals to r value"); } }

Output:

enter value of n
12
enter value of r
6
The value of 12p6 is : 665280.0
The value of 12c6 is : 924.0

Solution Worked 0 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Get Programming Help
Search

Play 2048 Game Online


Search Tags

    Find nCr using Java

    Find nPr using Java