如何在C++中实现阶乘函数?

Jon*_*len 18 c++ algorithm api-design

可能重复:
在C++中计算大因子
如何计算x的阶乘

如何在C++中实现阶乘函数?通过这个我的意思是使用任何参数检查正确实现它,并且错误处理逻辑适用于C++中的通用数学库.

Hov*_*yan 36

递归:

unsigned int factorial(unsigned int n) 
{
    if (n == 0)
       return 1;
    return n * factorial(n - 1);
}
Run Code Online (Sandbox Code Playgroud)

迭代:

unsigned int iter_factorial(unsigned int n)
{
    unsigned int ret = 1;
    for(unsigned int i = 1; i <= n; ++i)
        ret *= i;
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

编译时间:

template <int N>
struct Factorial 
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}
Run Code Online (Sandbox Code Playgroud)

  • 错误处理在哪里? (3认同)

Cub*_*bbi 25

除了明显的循环和递归之外,现代C++编译器支持伽玛函数tgamma(),与阶乘密切相关:

#include <iostream>
#include <cmath>
int main()
{
    int n;
    std::cin >> n;
    std::cout << std::tgamma(n+1) << '\n';
}
Run Code Online (Sandbox Code Playgroud)

测试运行:https://ideone.com/TiUQ3

  • @Jonathan Allen:什么样的"错误处理"?如果你问如何限制可接受的参数以仅允许结果可以完全表示为给定类型的值的无符号整数,那么答案将是`boost :: math :: factorial`的实现. (4认同)