In: Computer Science
Write a recursive methodcalledpermutationthataccepts two integersnandras parameters and returns the number of unique permutations ofritems from a group ofnitems. For given values ofnandr, this valuepermutation(n,r)can be computed as follows:
permutation(n,r)= n!/ (n-r)!
hint: permutation(6, 4)should return360. It may be helpful to note thatpermut(5, 3)returns60, or 360/6.
The recursive function to find permutation can be defined as follows:
int permutation(int n, int r)
{
if(r == 1)
return n; //stops recursion
return n*permutation(n-1, r-1);//recursive call
}
The required program and the corresponding output are as follows:
import java.io.*;
import java.lang.*;
class Testing{
static int permutation(int n, int r)
{
if(r == 1)
return n; //stops recursion
return n*permutation(n-1, r-1);//recursive call
}
public static void main(String args[]){
int nv,rv,p;
try{
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter value for n : ");
nv=Integer.parseInt(dis.readLine());//reading n value
System.out.println("Enter value for r : ");
rv=Integer.parseInt(dis.readLine());//reading r value
p=permutation(nv,rv);//function call
System.out.println("Nunber of unique permutations : " +p);
}
catch(Exception e){ System.out.println("Error : " +e); }
}
}
Output: