在 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.