Java program to find NCR factor of given number.



Calculate the combinations for C(n,r) = n! / ( r!(n - r)! ). For 0 <= r <= n.

package demo;
import java.util.Scanner;
public class Ncr
{
 public static void main(String[] args)
 {
  Scanner sc = new Scanner(System.in);
  int n, r, ncr;
  System.out.print("Enter any two numbers-");
  n = sc.nextInt();
  r = sc.nextInt();
  ncr = fact(n) / (fact(r) * fact(n - r));
  System.out.print("The NCR factor of " + n + " and " + r + " is " + ncr);
 }

 public static int fact(int n) 
 {
  int i = 1;
  while (n != 0) {
   i = i * n;
   n--;
  }
  return i;
 }
}

Output:
Enter any two numbers- 5
3
The NCR factor of 5 and 3 is 10
BUILD SUCCESSFUL (total time: 5 seconds)



No comments:

Post a Comment