📜  计算nCr值的程序

📅  最后修改于: 2021-06-25 09:43:46             🧑  作者: Mango

以下是二项式系数的常见定义。

  1. 可以将二项式系数C(n,k)定义为(1 + X)^ n展开中的X ^ k系数。
  2. 二项式系数C(n,k)还给出了可从n个对象中选择k个对象的方式数量,而无需考虑顺序。更正式地说,是n个元素集的k个元素子集(或k个组合)的数量。

给定两个数字n和r,求n C r的值
例子 :

Input :  n = 5, r = 2
Output : 10
The value of 5C2 is 10

Input : n = 3, r = 1
Output : 3

这个想法只是基于以下公式。

C++
// CPP program To calculate The Value Of nCr
#include 
using namespace std;
 
int fact(int n);
 
int nCr(int n, int r)
{
    return fact(n) / (fact(r) * fact(n - r));
}
 
// Returns factorial of n
int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i++)
        res = res * i;
    return res;
}
 
// Driver code
int main()
{
    int n = 5, r = 3;
    cout << nCr(n, r);
    return 0;
}


Java
// Java program To calculate
// The Value Of nCr
class GFG {
 
static int nCr(int n, int r)
{
    return fact(n) / (fact(r) *
                  fact(n - r));
}
 
// Returns factorial of n
static int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i++)
        res = res * i;
    return res;
}
 
// Driver code
public static void main(String[] args)
{
    int n = 5, r = 3;
    System.out.println(nCr(n, r));
}
}
 
// This code is Contributed by
// Smitha Dinesh Semwal.


Python 3
# Python 3 program To calculate
# The Value Of nCr
 
def nCr(n, r):
 
    return (fact(n) / (fact(r)
                * fact(n - r)))
 
# Returns factorial of n
def fact(n):
 
    res = 1
     
    for i in range(2, n+1):
        res = res * i
         
    return res
 
# Driver code
n = 5
r = 3
print(int(nCr(n, r)))
 
# This code is contributed
# by Smitha


C#
// C# program To calculate
// The Value Of nCr
using System;
 
class GFG {
 
static int nCr(int n, int r)
{
   return fact(n) / (fact(r) *
                 fact(n - r));
}
 
// Returns factorial of n
static int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i++)
        res = res * i;
    return res;
}
 
   // Driver code
   public static void Main()
   {
      int n = 5, r = 3;
      Console.Write(nCr(n, r));
   }
}
 
// This code is Contributed by nitin mittal.


PHP


Javascript


输出:
10

更高效的解决方案:
动态编程|集合9(二项式系数)
时空有效的二项式系数
所有关于二项式系数的文章