คำนวณ Combination ด้วย Factorial
ตัวอย่างคำนวณ combination (nCr) โดยใช้ factorial
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
int fact(int n) {
if (n == 0 || n == 1) return 1;
else return n * fact(n - 1);
}
int main() {
int n, r, result;
cout << "Enter n: ";
cin >> n;
cout << "\nEnter r: ";
cin >> r;
result = fact(n) / (fact(r) * fact(n-r));
cout << "\nThe result: " << result;
return 0;
}
ผลลัพธ์
Enter n: 10 Enter r: 4 The result: 210
ฟังก์ชัน fact() คำนวณ factorial แบบ recursive main() รับ n, r คำนวณ nCr = n! / (r! * (n-r)!)