+ 2

Can u pls write a java or c++ program to find permutations and combinations recursively

Pls also explain the logic of that program In this program we will take n and r as input from the user.

24th Jan 2017, 3:29 PM
Harsimran Kaur Bindra
Harsimran Kaur Bindra - avatar
1 Resposta
+ 6
//nPr = n! / (n-r)! //nCr = n! / (r! * (n-r)!) import java.util.Scanner; public class nPr { /*****************logic for nPr****************/ int value; int nPr_calculate(int n,int r) { if(n>=r && r>0) { value = 1; while(r>=1) { value = value*n; n--;r--; } } else if(n>0 && r==0) { value = 1; while(n!=1) { value *= n; n--; } } return value; } } /**********************************************/ /*****************logic for nCr****************/ public class nCr { int value, r_fact; int nCr_calculate(int n,int r) { if(n>=r && r>0) { value = r_fact= 1; while(r>=1) { value = value*n; r_fact = r_fact*r; n--;r--; } value = value/r_fact; } else if(n>0 && r==0) {value = 1;} return value; } /**********************************************/ } class calculate { public static void main(String args[]) { Scanner sc = new Scanner(System.in); nPr objP = new nPr(); nCr objC = new nCr(); int result=0; int n, r; System.out.println("Input Any Number For \"n\" : "); n=sc.nextInt(); System.out.println("Input Any Number For \"r\" : "); r=sc.nextInt(); result = objP.nPr_calculate(n,r); System.out.println(n + " P " + r + " = "+ result); result = objC.nCr_calculate(n,r); System.out.println(n + " C " + r + " = "+ result); } }
24th Jan 2017, 4:27 PM
Ajay Agrawal
Ajay Agrawal - avatar