ในบทความนี้ เราจะเข้าใจวิธีการคำนวณชุดค่าผสมโดยใช้ค่า 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