JAVA program to find the value of nPr(Permutation) using method

JAVA program to find the value of nPr(Permutation) using method

This JAVA program is to find the value of nPr(Permutation) using method.

For example, value of nPr(Permutation) using method of 5P3  will be nPr= 60.

Logic

To find permutation we use the concept of finding factorial of a number and use the standard formula for nPr=n!/(n-r)! .

Dry Run of the Program

Take input n=5 and r=3

npr=fact(n)/fact(n-r) i.e. npr=fact(5)/fact(5-3)  i.e. npr=fact(5)/fact(2)

Now function fact() is called.

We now calculate fact(5) and fact(2)

int fact(int n)

n=5

Initialize f=1;

1st iteration for(i=1;i<=n;i++)  i.e. for(i=1;1<=5;i++)

f=f*i; i.e. f=1*1  i.e. f=1

2nd iteration for(i=2;i<=n;i++)  i.e. for(i=2;2<=5;i++)

f=f*i; i.e. f=1*2  i.e. f=2

3rd iteration for(i=3;i<=n;i++)  i.e. for(i=3;3<=5;i++)

f=f*i; i.e. f=2*3  i.e. f=6

4th iteration for(i=4;i<=n;i++)  i.e. for(i=4;4<=5;i++)

f=f*i; i.e. f=6*4  i.e. f=24

5th iteration for(i=5;i<=n;i++)  i.e. for(i=5;5<=5;i++)

f=f*i; i.e. f=24*5  i.e. f=120

Now we break out of the for loop as i will now be greater than n(5).

In a similar way, we calculate fact(2) for which answer will be 2

Hence 5p3 = 120/2 = 60.

As practice you can run the same program with the different ways of using methods.

Program

import java.util.*;

class mr4
{
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
    		System.out.println("Enter a number N");
    		int n=sc.nextInt();
    		System.out.println("Enter a number R");
    		int r=sc.nextInt();
  		int npr=fact(n)/fact(n-r);

    		System.out.println("Value of "+n+"P"+r+" = "+npr);
    	}
	
	static int fact(int n)
	{
		int i,f=1;
    		for(i=1;i<=n;i++)
    		{
        		f=f*i;
    		}	
    		return f;
	}
}

Output

Share Me!