# Java program to calculate the value of nPr

Given the values of N and R, we have to calculate the value of nPr.
Submitted by Nidhi, on March 01, 2022

Problem Solution:

In this program, we will read N, R from the user and calculate the nPr.

nPr:

The nPr is the permutation of arrangement of r objects from a set of n objects, into an order or sequence. The formula to find permutation is: nPr = (n!) / (n-r)!

Program/Source Code:

The source code to calculate the value of nPr is given below. The given program is compiled and executed successfully.

```// Java program to calculate the
// value of nPr

import java.util.Scanner;

public class Main {
static int getFactorial(int num) {
int f = 1;
int i = 0;

if (num == 0)
return 1;

for (i = 1; i <= num; i++)
f = f * i;

return f;
}

public static void main(String[] args) {
Scanner SC = new Scanner(System.in);

int n = 0;
int r = 0;

int nPr = 0;

System.out.printf("Enter the value of N: ");
n = SC.nextInt();

System.out.printf("Enter the value of R: ");
r = SC.nextInt();

nPr = getFactorial(n) / getFactorial(n - r);

System.out.printf("The nPr is: %d\n", nPr);
}
}
```

Output:

```Enter the value of N: 7
Enter the value of R: 4
The nPr is: 840
```

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains two static methods getFactorial() and main().

The getFactorial() method is used to calculate the factorial of the given number.

The main() method is an entry point for the program. Here, we read values N, R from the user using the Scanner class. Then we calculated the nPr and printed the result.

Preparation

What's New

Top Interview Coding Problems/Challenges!