简体   繁体   English

是否有内置 function 来计算 C++ 中的 nCr?

[英]Is there a built-in function to calculate nCr in C++?

In python 3.8, there is a built-in function for calculating the number of combinations ( nCr(n, k) ):在 python 3.8 中,有一个内置的 function 用于计算组合数( nCr(n, k) ):

>>>from math import comb
>>>comb(10,3)
120

Is there any such function in C++? C++中有没有这样的function?

The beta function from the mathematical library can be used to express binomial coefficients (aka nCr).数学库中的beta function 可用于表示二项式系数(又名 nCr)。

double binom(int n, int k) {
    return 1/((n+1)*std::beta(n-k+1,k+1));
}

Source. 资源。

This function is available either with C++17 or as part of an implementation of the mathematical special functions extensions for C++ (ISO/IEC 29124:2010).此 function 可与 C++17 一起使用,也可作为 C++ (ISO/IEC 29124:2010) 的数学特殊函数扩展实现的一部分In the latter case, your implementation may require you to #define __STDCPP_WANT_MATH_SPEC_FUNCS__ 1 before including the <cmath> header for the function to be available.在后一种情况下,您的实现可能需要您在包含<cmath> header 之前#define __STDCPP_WANT_MATH_SPEC_FUNCS__ 1以使 function 可用。

Note that, unlike Python, C++ does not have built-in support for big integer numbers, so using floating point arithmetic is probably a good choice here in the first place.请注意,与 Python 不同,C++ 没有对大 integer 数字的内置支持,因此首先使用浮点运算可能是一个不错的选择。

Disclaimer: If using C++17, use the beta function as described by @ComicSansMS Otherwise you can use the tgamma or even lgamma functions if using C++11免责声明:如果使用 C++17,请使用 @ComicSansMS 所述的beta function否则,如果使用 C++11,则可以使用tgamma甚至lgamma函数

Using lgamma :使用lgamma

double comb_l(double n, double k) {
    return std::exp(std::lgamma(n + 1)- std::lgamma(k + 1) - std::lgamma(n - k + 1));
}

Using tgamma :使用tgamma

double comb_t(double n, double k) {
        return std::tgamma(n + 1) / std::tgamma(k + 1) / std::tgamma(n - k + 1));
}

In python 3.8, there is a built-in function for calculating the number of combinations ( nCr(n, k) ):在 python 3.8 中,有一个内置的 function 用于计算组合数( nCr(n, k) ):

>>>from math import comb
>>>comb(10,3)
120

Is there any such function in C++? C++中有没有这样的function?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM