【问题标题】:How do you implement the factorial function in C++? [duplicate]你如何在 C++ 中实现阶乘函数? [复制]
【发布时间】:2011-08-08 23:19:27
【问题描述】:

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

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

【问题讨论】:

标签: c++ algorithm api-design


【解决方案1】:

递归:

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
}

【讨论】:

  • 这使用了一些非常不必要的递归。
  • 您也可以轻松应用迭代方法。
  • 错误处理在哪里?
  • @Jonathan 这个问题是在我回答后编辑的,并更新了我想的错误处理要求
【解决方案2】:

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

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

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

【讨论】:

  • 这对于教如何在这种函数中进行错误处理是没有用的。
  • @Jonathan Allen:什么样的“错误处理”?如果您询问如何限制可接受的参数以仅允许其结果可精确表示为给定类型的值的无符号整数,那么答案将是 boost::math::factorial 的实现。
  • @Cubbi 我相信ideone.com 破坏了你的代码。
  • @Cubbi 所以我无权问这个问题,但我们正在讨论你的en.cppreference.com 编辑之一,我想你可能愿意为我们澄清:stackoverflow.com/q/38402133/2642059跨度>
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多