求N的阶乘以及N的阶乘的和

#include<iostream>
using namespace std;

//求N的阶乘 如fac1(5) 5x4x3x2x1
int fac1(int n)
{
    if (n < 0) {
        return 0;
    }

    if (n == 1 || n == 0) {
        return 1;
    }

    return n * fac1(n - 1);
}

//求N的阶乘 如fac1(5) 5x4x3x2x1
int fac2(int n)
{
    if (n < 0) {
        return 0;
    }

    if (n == 1 || n == 0) {
        return 1;
    }
    int result = 1;
    for (int i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}

// N项阶乘的和,如sumFac(5) 5x4x3x2x1 + 4x3x2x1 + 3x2x1 + 2x1 + 1 + 1
int sumFac(int n)
{
    if (n < 0) {
        return 0;
    }

    if (n == 0) {
        return 1;
    }

    int result = 1;
    int total = 1;

    for (int i = 1; i <= n; i++) {
        result *= i;
        total += result;
    }

    return total;
}

int main(int argc, const char * argv[])
{
    int fac1Value = fac1(5);
    int fac2Value = fac2(7);
    int sum = sumFac(20);

    cout << "5的阶乘 = " << fac1Value << "\n";
    cout << "7项阶乘 = " << fac2Value << "\n";
    cout << "10项阶乘的和 = " << sum << endl;

    return 0;
}
点赞