在C ++中计算nCr值的程序

给定n C r,其中C表示组合,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 计算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;
//它将为n计算阶乘
int cal_n(int n){
   int temp = 1;
   for (int i = 2; i <= n; i++)
      temp = temp * i;
   return temp;
}
//计算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