Trong bài này, chúng ta sẽ hiểu cách tính tổ hợp sử dụng các giá trị n và r. NCr được tính bằng công thức -
(factorial of n) / (factorial of (n-r))
Dưới đây là một minh chứng về điều tương tự -
Đầu vào
Giả sử đầu vào của chúng tôi là -
Value of n : 6 Value of r : 4
Đầu ra
Đầu ra mong muốn sẽ là -
The nCr value is : 15
Thuật toán
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
Ví dụ 1
Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi
.
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));
}
} Đầu ra
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
Ví dụ 2
Ở đây, số nguyên đã được xác định trước đó và giá trị của nó được truy cập và hiển thị trên bảng điều khiển.
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));
}
} Đầu ra
The n and r values are defined as 6 and 4 The combination value for the given input is = 15