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

时间:2014-08-14 02:47:37

标签: c++ factorial

我想分析一下我的代码算法的复杂性。因此,我必须有两个不同的程序,它们具有相同的功能,可以让我开始。

目前这是我自己的代码。

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

最好是嵌套循环。

#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;
}

3 个答案:

答案 0 :(得分: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位整数是一种练习。

答案 1 :(得分: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;
}

答案 2 :(得分: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;
}