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 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.