Q:

Java program to calculate the value of nPr

belongs to collection: Java Basic Programs

0

Java program to calculate the value of nPr

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will read NR 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 NR from the user using the Scanner class. Then we calculated the nPr and printed the result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to calculate the product of two binar... >>
<< Java program to calculate the value of nCr...