在 C++ 中计算数字的阶乘

本文将介绍几种在 C++ 中如何计算数字阶乘的方法。

使用迭代法在 C++ 中计算数字的阶乘

该数字的阶乘是通过将所有整数从一个开始,包括给定数字相乘而得出的。注意,直接算法是使用循环语句之一使用迭代。在下面的示例代码中,我们实现了一个 while 循环,该循环将相乘的值累加到一个变量中,然后将按值生成的整数返回给调用者。请注意,循环在每个循环中减小数字,并且在数值减小之前,使用 n-- 表达式存储该值。

#include <iostream>#include <string>#include <vector>using std::cout; using std::endl;
using std::string; using std::cin;
using std::vector;
int factorial1(int n)
{
    int ret = 1;
    while (n > 1)
        ret *= n--;
    return ret;
}
template<typename T>
void printVector(vector<T> &vec)
{
    for (const auto &item : vec) {
        cout << item << ", ";
    }
    cout << endl;
}
int main(){
    vector<int> vec = {1,2,3,4,5,6,7,8,9,10};
    printVector(vec);
    for (const auto &item : vec) {
        cout << factorial1(item) << ", ";
    }
    cout << endl;
    return EXIT_SUCCESS;
}

输出:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800,

使用递归方法计算数字的阶乘

另一种解决方案是采用递归函数调用进行阶乘计算。递归是该函数从其主体进行调用的功能。递归函数的主要部分是定义一个条件,以确保它返回到调用方并且不会陷入无限循环样式的行为中。在这种情况下,我们指定 if 条件来表示应进行递归调用的状态。否则,该函数应返回 1。

#include <iostream>#include <vector>using std::cout; using std::endl;
using std::string; using std::cin;
using std::vector;
int factorial2(int n)
{
    if (n > 1)
        return factorial2(n-1) * n;
    return 1;
}
template<typename T>
void printVector(vector<T> &vec)
{
    for (const auto &item : vec) {
        cout << item << ", ";
    }
    cout << endl;
}
int main(){
    vector<int> vec = {1,2,3,4,5,6,7,8,9,10};
    printVector(vec);
    for (const auto &item : vec) {
        cout << factorial2(item) << ", ";
    }
    cout << endl;
    return EXIT_SUCCESS;
}

输出:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800,

或者,我们可以将递归函数合并为单行实现,其中 ?:表达式计算给定数字等于 0 还是 1,在这种情况下该函数返回 1。如果条件为假,则进行递归调用,并继续执行新的函数栈帧,直到条件为真为止。示例代码输出已声明的向量中每个元素的阶乘。

#include <iostream>#include <vector>using std::cout; using std::endl;
using std::string; using std::cin;
using std::vector;
int factorial3(int n)
{
    return (n==1 || n==0) ? 1 : n * factorial3(n - 1);
}
template<typename T>
void printVector(vector<T> &vec)
{
    for (const auto &item : vec) {
        cout << item << ", ";
    }
    cout << endl;
}
int main(){
    vector<int> vec = {1,2,3,4,5,6,7,8,9,10};
    printVector(vec);
    for (const auto &item : vec) {
        cout << factorial3(item) << ", ";
    }
    cout << endl;
    return EXIT_SUCCESS;
}

输出:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800,