在 C++ 中計算 nCr 值的程式
其中,nCr 代表組合,n 代表總數,r 代表從集合中選擇的數量,任務是計算 nCr 的值。
組合是不用考慮排列順序從給定的資料中選擇資料。排列和組合不同之處在於,排列是排列的過程,而組合是從給定集合中選擇元素的過程。
排列的公式為 -
nPr = (n!)/(r!*(n-r)!)
示例
Input-: n=12 r=4 Output-: value of 12c4 is :495
演算法
Start Step 1 -> Declare function for calculating factorial int cal_n(int n) int temp = 1 Loop for int i = 2 and i <= n and i++ Set temp = temp * i End return temp step 2 -> declare function to calculate ncr int nCr(int n, int r) return cal_n(n) / (cal_n(r) * cal_n(n - r)) step 3 -> In main() declare variable as int n = 12, r = 4 print nCr(n, r) Stop
示例
#include <bits/stdc++.h>
using namespace std;
//it will calculate factorial for n
int cal_n(int n){
int temp = 1;
for (int i = 2; i <= n; i++)
temp = temp * i;
return temp;
}
//function to calculate ncr
int nCr(int n, int r){
return cal_n(n) / (cal_n(r) * cal_n(n - r));
}
int main(){
int n = 12, r = 4;
cout <<"value of "<<n<<"c"<<r<<" is :"<<nCr(n, r);
return 0;
}輸出
value of 12c4 is :495
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP