C ++阶乘的总和 - 请求第二个代码

问题描述 投票:-5回答:3

我想分析我的代码算法的复杂性。因此,我必须有2个不同的程序,给出相同的功能,让我开始。

目前这是我自己的代码。

我不确定是否允许我希望有人可以自愿编写自己的代码来计算我作为第二个程序代码的阶乘总和。

最好是嵌套循环。

#include <iostream>
using namespace std;
int main()
{
    int val;
    int i;
    int a = 0;
    int c = 1;
    cout << "Please enter a number: ";
    cin >> val;
    cout << endl;

    for (i = 1; i <= val; i++)
    {
        c = c * i;
        a = a + c;
    }
    cout << "The sum of the factorials is " << a << endl;

    system("pause");
    return 0;
}
c++ factorial
3个回答
1
投票
#include <iostream>
using namespace std;
int main()
{
    int val;
    cout << "Please enter a number: ";
    cin >> val;
    cout << endl;

    static const int results[] = {
       0, 1, 3, 9, 33, 153, 873, 5913, 46233, 409113,
       4037913, 43954713, 522956313
    };

    cout << "The sum of the factorials is " << results[val < 0 ? 0 : val] << endl;

    system("pause");
    return 0;
}

请注意,我复制了原始程序中的缺陷,如果用户输入0,则会导致返回错误的值。

此备用版本假定32位整数,因为它利用了溢出行为。扩展到64位整数仍然是一个练习。


0
投票

我不明白你用另一种嵌套方式做什么,但我希望这可以帮助...

#include <iostream>
using namespace std;

int main()
{
    int val;
    int i;
    int a = 0;
    int c = 1;
    cout << "Please enter a number: ";
    cin >> val;
    cout << endl;

    for (i = 1; i <= val; i++){
        c *= i;
        a += c;
    }
    int c2=1;
    for (i = val; i > 1; i--){
        c2*=i;
        c2++;
    }

    cout << "The sum of the factorials is " << a << endl;
    cout << "The sum of the factorials is " << c2 << endl;

    system("pause");
    return 0;
}

0
投票
    #include <iostream>

using namespace std;

int main()
{
    int suma = 0;
    int n = 0;

    cout << "Sum of factorials\n";
    cout << "-------------------------------\n";
    cout << "Insert number of n: ";
    cin >> n;

    int i = 1;
    while (i <= n)
    {
        int factorial = 1;
        for(int j=1; j<=i; j++)
        {
            factorial = factorial * j;
        }

        suma += factorial;
        i++;
    }

    cout << "Sum of factorials is: " << suma;

    system("pause");
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.