如何在C ++中实现阶乘函数? [重复]

时间:2022-02-12 05:28:56

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

可能的重复:在C ++中计算大因子如何计算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++.

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

3 个解决方案

#1


34  

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


19  

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

除了明显的循环和递归之外,现代C ++编译器支持gamma函数作为tgamma(),与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

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

#3


0  

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

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

#1


34  

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


19  

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

除了明显的循环和递归之外,现代C ++编译器支持gamma函数作为tgamma(),与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

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

#3


0  

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

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