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

时间:2011-04-19 19:46:03

标签: c++ algorithm api-design

  

可能重复:
  Calculating large factorials in C++
  Howto compute the factorial of x

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

3 个答案:

答案 0 :(得分:35)

递归:

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
}

答案 1 :(得分:24)

除了明显的循环和递归之外,现代C ++编译器支持将gamma函数作为tgamma(),与factorial密切相关:

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

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

答案 2 :(得分:0)

如果安装了Boost,您可能需要查看boost/math/special_functions/factorials.hpp。您可以在以下网址阅读:Boost Factorial