The given Java code calculates the permutation and combination of two numbers n and r.
fact
function is used to calculate the factorial of a number, which is defined as the product of all positive integers less than or equal to that number. If the value of val
is 0 or 1, the function returns 1. For any other value of val
, the function returns the product of val
and the factorial of val-1
.
main
method takes two inputs, n
and r
, from the user and calculates the combination and permutation of the two numbers. The combination is calculated by dividing the factorial of n
by the product of the factorials of r
and n-r
. The permutation is calculated by dividing the factorial of n
by the factorial of n-r
.
Finally, the calculated values of combination and permutation are displayed to the user.
import java.util.Scanner;
public class PermutationCombination {
private static int fact(int val) {
if (val == 0 || val == 1)
return 1;
else
return val * fact(val - 1);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n, r, combination, permutation;
System.out.print("Enter value of n : ");
n = scan.nextInt();
System.out.print("Enter value of r : ");
r = scan.nextInt();
combination = fact(n) / (fact(r) * fact(n - r));
permutation = fact(n) / fact(n - r);
System.out.println("\nCombination : " + combination);
System.out.print("Permutation : " + permutation);
}
}
Enter value of n : 8
Enter value of r : 6
Combination : 28
Permutation : 20160