Program to calculate the value of nPr

In this post we will understand about nPr and then will write the program in Java to calculate the value of nPr.

Given: Two numbers n and r, the task is to find the value of nPr.

Problem:

nPr represents n permutation r which is calculated as n!/(n-k)!. Permutation refers to the process of arranging all the members of a given set to form a sequence. The number of permutations on a set of n elements is given by n!, where “!” represents factorial.

nPr = n! / (n – r)!

Program to calculate value of  nPr in Java:

import java.util.*; 

public class GFG { 

    static int fact(int n)
    {
        if (n <= 1)
            return 1;
        return n * fact(n - 1);
    } 

    static int nPr(int n, int r)
    {
        return fact(n) / fact(n - r);
    }
 
    public static void main(String args[])
    {
        int n = 5;
        int r = 2; 

        System.out.println(n + "P" + r + " = " + nPr(n, r));

    }

}

OUTPUT:

5P2 = 20

Optimization for multiple queries of nPr

If there are multiple queries for nPr, we may precompute factorial values and use same for every call. This would avoid computation of same factorial values again and again.

Leave a Comment