Permute Number in Java using Formula

Permutation of a number can be calculated in Java using the standard permutation formula.

The formula for nPr is n!/(n-r)! That is what we are going to use here.





import java.util.*;
class Permute
{
    public static void main(String args[])
    {
    Scanner s=new Scanner(System.in);

    System.out.println("Enter the value of n");
    int n=s.nextInt();
   
   
    System.out.println("Enter the permutation suffix (r)");
    int r=s.nextInt();

    long res=1;

        if(n>=r)
        {
            res=getFact(n)/getFact(n-r);
            System.out.println("The permutation is "+res);
        }
        else System.out.println("r cannot be greater than n");
   
    }

    public static long getFact(int n)
    {
        long f=1;

        for(int i=n;i>=1;i--)
        {
        f*=i;
        }

    return f;
    }
}

Sample Output


Enter the value of n
5
Enter the permutation suffix (r)
2
The permutation is 20

Analysis

n>=r: n cannot be greater than r in case of permuting nPr.
getFact(n)/getFact(n-r): It is nothing but the above formula (n!/(n-r)!).
getFact(int n): The method takes a number and return it's factorial. This is actually discussed in finding the factorial of a number in Java

This is how we can simply permute a number in Java just by knowing the formula.


Posted by at on

Tags: Playing with Numbers,