# Calculate Permutation and Combination in Java

Permutation and combination of two numbers n and r are calculated as nPr = !n / !(n – r) and nCr = !n / (!(n – r) * !r) where permutation is denoted as nPr and combination is denoted as nCr.

The nPr means permutation of n and r and nCr means combination of n and r.

Also note that !n means the factorial of n.

Factorial of N is the product of all the integers from 1 to N.

Factorial of 0 is 1.

Write a program in Java to accept two numbers n and r from the user and calculate their permutation and combination by using the above formula.

Example:
INPUT:
N=11
R=10
OUTPUT:
nPr is:39916800
nCr is:11

Display an appropriate message if n or r is less than 0.

``````import java.io.*;
class PermutationCombination{
public static void main(String args[])throws IOException{
System.out.print("n = ");
System.out.print("r = ");
if(n < 0 || r < 0){
System.out.println("Invalid values!");
return;
}
long npr = f(n) / f(n - r);
long ncr = f(n) / (f(n - r) * f(r));
System.out.println("nPr = " + npr);
System.out.println("nCr = " + ncr);
}
public static long f(int n){
long result = 1L;
for(int i = 1; i <= n; i++)
result *= i;
return result;
}
}``````

This site uses Akismet to reduce spam. Learn how your comment data is processed.