Permutations in which n people can occupy r seats in a classroom

Java Program to find the Permutations in which n people can occupy r seats in a classroom

Our Aim is to write a Java code to find all the possible permutations in which (n) people can occupy (r) number of seats in a classroom.

Suppose (n) number  students are looking to find (r) seats in a classroom so how will they do it . They will do it with simple formula which is given by 

nPr =    n! / (n-r)!

Example :

5P2 means a permutation of 5 things taken 2 at a time. Start with the first number (which in this case is 5), and count down for a total of 2 numbers: 5P2 = 5*4 = 20.

java program for finding the permutations in which n people can occupy r seats in a classroom

Implementation:

  •  Start
  •  Ask the user to input n number of people and the number of seats as r.
  •  Calculate permutation p(n,r).
  •  Calculate permutation by using formula P(n,r) = n! / (n-r)!
  • Print the calculated result.
  •  End

Java code :

import java.util.*;  
import java.io.*;

    class PrepInsta
    {  
      public static void main(String[] args)  
        {  
            int nrperfact1fact2;  
            Scanner sc =  new Scanner(System.in);  
            System.out.println(“Enter the Value of n and r”);  
            n = sc.nextInt();  
            r = sc.nextInt();  
            fact1 = n;  
            for (int i = n – 1; i >= 1; i=i-1)  
            {  
                fact1 = fact1 * i;  //calculating factorial (n!)
            }  
            int number;  
            number = n – r;  
            fact2 = number;  
            for (int i = number – 1; i >= 1; i=i-1)  
            {  
                fact2 = fact2 * i;  //calculating factorial ((n-r)!)
            }  
            per = fact1 / fact2;  //calculating  nPr
            System.out.println(per+“ways”);  
    }  
}  
Output:
Enter the Value of n and r
5
2
20 ways