目录

  • C++中计算整数阶乘的几种方法
    • 1. 递归方法
    • 2. 迭代方法
    • 3. 使用模板元编程(编译时计算)
    • 4. 使用constexpr函数(C++11及以上)
    • 5. 使用动态规划(预先计算并存储)
    • 注意事项

C++中计算整数阶乘的几种方法

阶乘是数学中常见的运算,表示从1到该整数的所有正整数相乘。在C++中,有多种方法可以实现阶乘计算。以下是几种常见的方法:

1. 递归方法

#include <iostream>

unsigned long long factorialRecursive(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return n * factorialRecursive(n - 1);
}

int main() {
    int num = 5;
    std::cout << "Factorial of " << num << " is " << factorialRecursive(num) << std::endl;
    return 0;
}

2. 迭代方法

#include <iostream>

unsigned long long factorialIterative(int n) {
    unsigned long long result = 1;
    for (int i = 1; i <= n; ++i) {
        result *= i;
    }
    return result;
}

int main() {
    int num = 5;
    std::cout << "Factorial of " << num << " is " << factorialIterative(num) << std::endl;
    return 0;
}

3. 使用模板元编程(编译时计算)

#include <iostream>

template <int N>
struct Factorial {
    static const unsigned long long value = N * Factorial<N - 1>::value;
};

template <>
struct Factorial<0> {
    static const unsigned long long value = 1;
};

int main() {
    const int num = 5;
    std::cout << "Factorial of " << num << " is " << Factorial<num>::value << std::endl;
    return 0;
}

4. 使用constexpr函数(C++11及以上)

#include <iostream>

constexpr unsigned long long factorialConstexpr(int n) {
    return n <= 1 ? 1 : n * factorialConstexpr(n - 1);
}

int main() {
    constexpr int num = 5;
    std::cout << "Factorial of " << num << " is " << factorialConstexpr(num) << std::endl;
    return 0;
}

5. 使用动态规划(预先计算并存储)

#include <iostream>
#include <vector>

std::vector<unsigned long long> factorialDP(int n) {
    std::vector<unsigned long long> dp(n + 1, 1);
    for (int i = 2; i <= n; ++i) {
        dp[i] = i * dp[i - 1];
    }
    return dp;
}

int main() {
    int num = 5;
    auto factorials = factorialDP(num);
    std::cout << "Factorial of " << num << " is " << factorials[num] << std::endl;
    return 0;
}

注意事项

  1. 阶乘结果增长非常快,20!就已经超过了64位无符号整数的最大值(2^64-1)
  2. 对于大数阶乘,需要考虑使用大整数库或字符串表示
  3. 递归方法虽然简洁,但对于大数可能会导致栈溢出
  4. 负数的阶乘在数学上没有定义,程序中应添加输入验证

选择哪种方法取决于具体需求,如性能要求、编译时计算需求等。

更多推荐