简体   繁体   English

C++ 中是否有任何内置的阶乘函数?

[英]Is there any built-in factorial function in c++?

I have searched but I was not able to find this.我已经搜索过,但我找不到这个。 Would anyone please tell me that if there is any built-in factorial function in c++ ?谁能告诉我,c++ 中是否有任何内置的阶乘函数?

Although there is no C function defined specifically for computing factorials, C math library lets you compute gamma function .尽管没有专门为计算阶乘定义的 C 函数,但 C 数学库可让您计算gamma 函数 Since Г(n) = (n-1)!由于 Г(n) = (n-1)! for positive integers, using tgamma of i+1 yields i!对于正整数,使用i+1 tgamma产生i! . .

If you use a user-defined factorial function, this would print identical numbers:如果您使用用户定义的阶乘函数,这将打印相同的数字:

for (int i = 1 ; i != 10 ; i++) {
    printf("%lld %f\n", factorial(i), tgamma(i+1));
}

Demo.演示。

1 1.000000
2 2.000000
6 6.000000
24 24.000000
120 120.000000
720 720.000000
5040 5040.000000
40320 40320.000000
362880 362880.000000

Note: Considering how easy it is to code up factorial function, using gamma to compute factorials is a lot like killing a fly with a sledgehammer.注意:考虑到编写阶乘函数是多么容易,使用 gamma 计算阶乘很像用大锤杀死一只苍蝇。

不,标准库中没有这样的功能。

不,在标准 C++ 中,没有像 factorial 这样的函数,但是你可以在 boost 库中找到相同的功能: boost::math::factorial

STL doesn't provide function for Factorial but you can calculate in one line recursively: STL 不提供 Factorial 函数,但您可以递归地在一行中计算:

int fact(int n){

     return (n==0) || (n==1) ? 1 : n* fact(n-1);
}

there is no function present for find factorial in c++ STL.在 C++ STL 中没有用于 find factorial 的函数。 you should write your own function for find factorial您应该编写自己的函数来查找阶乘

Writing a slow version of factorial even with DP in C or C++ is easy.即使使用 C 或 C++ 中的 DP 编写阶乘的慢版本也很容易。 However, there is a much faster algorithm implemented in Python 3:然而,在 Python 3 中实现了一个更快的算法:

See https://hg.python.org/cpython/file/7937aa6b7e92/Modules/mathmodule.c#l1218https://hg.python.org/cpython/file/7937aa6b7e92/Modules/mathmodule.c#l1218

So, it would be good to add it to the STL imho.因此,最好将其添加到 STL imho。

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

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