Java 程序执行 nCr(r 组合)


本文中,我们将了解如何使用 n 和 r 值计算组合。nCr 的计算公式为:

(factorial of n) / (factorial of (n-r))

以下是对其演示:

输入

假设我们的输入为:

Value of n : 6
Value of r : 4

输出

所需输出为:

The nCr value is : 15

算法

Step 1 - START
Step 2 - Declare two integer values namely n and r.
Step 3 - Read the required values from the user/ define the values
Step 4 - Define two functions, one function to calculate the factorial of n and (n-r) and other
to compute the formula : (factorial of n) / (factorial of (n-r)) and store the result.
Step 5 - Display the result
Step 6 - Stop

示例 1

在此,用户根据提示输入内容。你可以在我们的编程实践工具中 run button中尝试此示例。

import java.util.*;
public class Combination {
   static int Compute_nCr(int n, int r){
      return my_factorial(n) / (my_factorial(r) *
      my_factorial(n - r));
   }
   static int my_factorial(int n){
      int i, my_result;
      my_result = 1;
      for (i = 2; i <= n; i++)
         my_result = my_result * i;
      return my_result;
   }
   public static void main(String[] args){
      int n,r;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the value of n : ");
      n = my_scanner.nextInt();
      System.out.print("Enter the value of r : ");
      r = my_scanner.nextInt();
      System.out.println("The combination value for the given input is = "+Compute_nCr(n, r));
   }
}

输出

Required packages have been imported
A reader object has been defined
Enter the value of n : 6
Enter the value of r : 4
The combination value for the given input is = 15

示例 2

此处,整数已事先定义好,其值已访问并显示在控制台上。

public class Combination {
   static int Compute_nCr(int n, int r){
      return my_factorial(n) / (my_factorial(r) *
      my_factorial(n - r));
   }
   static int my_factorial(int n){
      int i, my_result;
      my_result = 1;
      for (i = 2; i <= n; i++)
         my_result = my_result * i;
      return my_result;
   }
   public static void main(String[] args){
      int n,r;
      n = 6 ;
      r = 4 ;
      System.out.println("The n and r values are defined as " +n + " and " +r);
      System.out.println("The combination value for the given input is = "+Compute_nCr(n, r));
   }
}

输出

The n and r values are defined as 6 and 4
The combination value for the given input is = 15

更新于:22-02-2022

420 次浏览

开启你的 职业

完成课程获得认证

开始
广告