在 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

更新於:2019 年 9 月 23 日

3K+ 瀏覽

開啟你的 職業

完成課程獲得認證

開始吧
廣告
© . All rights reserved.