执行 nCr(r 组合)的 Java 程序

javaobject oriented programmingprogramming更新于 2024/4/15 7:40:17

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

(n 的阶乘) / ((n-r) 的阶乘)

下面是相同的演示 −

输入

假设我们的输入是 −

n 的值:6
r 的值:4

输出

所需的输出将是 −

nCr 值为:15

算法

步骤 1 - 开始
步骤 2 - 声明两个整数值,即 n 和 r。
步骤 3 - 从用户处读取所需值/定义值
步骤 4 - 定义两个函数,一个函数用于计算 n 和 (n-r) 的阶乘,另一个函数用于计算公式:(n 的阶乘)/((n-r) 的阶乘) 并存储结果。
步骤 5 - 显示结果
步骤 6 - 停止

示例 1

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

相关文章


有用资源