How do you implement the factorial function in C++? [duplicate]

六眼飞鱼酱① 提交于 2019-11-27 05:41:24

问题


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

How do you implement the factorial function in C++? And by this I mean properly implement it using whatever argument checking and error handling logic is appropriate for a general purpose math library in C++.


回答1:


Recursive:

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

Iterative:

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

Compile time:

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
}



回答2:


Besides the obvious loops and recursions, modern C++ compilers support the gamma function as tgamma(), closely related to factorial:

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

test run: https://ideone.com/TiUQ3




回答3:


You might want to take a look at boost/math/special_functions/factorials.hpp if you have Boost installed. You can read about it at: Boost Factorial



来源:https://stackoverflow.com/questions/5721796/how-do-you-implement-the-factorial-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!