我想分析一下我的代码算法的复杂性。因此,我必须有两个不同的程序提供相同的功能,才能让我开始。
目前是我自己的代码。
我不确定是否允许,我希望有人可以自愿提供他自己的方式代码来为我计算阶乘的总和作为第二个程序代码。
最好是嵌套循环。
#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;
}
#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位整数是一个练习。
我不明白你用另一种嵌套的方式做什么,但我希望这能帮助…
#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;
}
#include <iostream>
using namespace std;
int main()
{
int suma = 0;
int n = 0;
cout << "Sum of factorialsn";
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;
}