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

标签 c++ algorithm api-design

Possible Duplicates:
Calculating large factorials in C++
Howto compute the factorial of x

如何在 C++ 中实现阶乘函数?我的意思是使用适用于 C++ 中的通用数学库的任何参数检查和错误处理逻辑来正确实现它。

最佳答案

递归:

unsigned int factorial(unsigned int n) 
{
    if (n == 0)
       return 1;
    return n * factorial(n - 1);
}

迭代:

unsigned int iter_factorial(unsigned int n)
{
    unsigned int ret = 1;
    for(unsigned int i = 1; i <= n; ++i)
        ret *= i;
    return ret;
}

编译时间:

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
}

关于c++ - 你如何在 C++ 中实现阶乘函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5721796/

相关文章:

c++ - gcc 可以使用旧的第三方库编译 C++17 代码吗?

c++ - C++ 中未对齐访问的正确性

python - 将普通代码转换为 3AC - 三地址代码

rest - 在 RESTful API 中,DELETE 调用应该是递归的吗?

api-design - Swagger 中的基本 URL 可以更改吗?

C++链接器设计问题

python - 传送旅行者,随着时间的推移优化利润问题

algorithm - 哪个集群节点应该处于事件状态?

mysql - 如何处理 REST API 端点上的结果过滤?

c++ - 非 POD 类型的复制构造函数和普通构造函数