[英]Is there a built-in function to calculate nCr in C++?
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));
}
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.