이 기사에서는 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
여기에서 입력은 프롬프트에 따라 사용자가 입력하고 있습니다. 우리코딩 그라운드 도구에서 이 예제를 라이브로 사용해 볼 수 있습니다.
.
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