已知n是整数,计算1+2!+3!+...+n!,并给出最大能够计算的n值是多少?
1. 假设n是int类型,系统用32位表示int类型。代码如下:
#include <stdio.h>
int main()
{
int n,sum1,sum=1,fact=1;
int step;
for(n=2; n<100; n++) {
step = fact;
fact *= n;
if( step>fact) break;
sum1 = sum;
sum += fact;
if (sum1>sum) {
sum = sum1;
break;
}
}
printf("sum=%d\n", sum);
printf("n=%d\n", n-1);
return 0;
}
程序运行结果如下图所示。
2. 假设n是long long int类型,即64位整数。代码如下:
#include <stdio.h>
int main()
{
long long int sum1,sum=1,fact=1;
long long int step;
int n;
for(n=2; n<100; n++) {
step = fact;
fact *= n;
if( step>fact) break;
sum1 = sum;
sum += fact;
if (sum1>sum) {
sum = sum1;
break;
}
}
printf("sum=%lld\n", sum);
printf("n=%d\n", n-1);
return 0;
}
程序运行结果如下图所示。
3. 假设n是unsigned int类型,即32位无符号整数。代码如下:
#include <stdio.h>
int main()
{
unsigned int n,sum1,sum=1,fact=1;
unsigned int step;
for(n=2; n<100; n++) {
step = fact;
fact *= n;
if( step>fact) break;
sum1 = sum;
sum += fact;
if (sum1>sum) {
sum = sum1;
break;
}
}
printf("sum=%u\n", sum);
printf("n=%d\n", n-1);
printf("%d!=%u\n", n-1, step);
return 0;
}
程序运行结果如下图所示。
4. 假设n是unsigned long long int类型,即64位无符号整数。代码如下:
#include <stdio.h>
int main()
{
unsigned long long int sum1,sum=1,fact=1;
unsigned long long int step;
int n;
for(n=2; n<100; n++) {
step = fact;
fact *= n;
if( step>fact) break;
sum1 = sum;
sum += fact;
if (sum1>sum) {
sum = sum1;
break;
}
}
printf("sum=%llu\n", sum);
printf("n=%d\n", n-1);
printf("%d!=%llu\n", n-1, step);
return 0;
return 0;
}
程序运行结果如下图所示。
参考文献:
[1]李红卫,李秉璋.?C程序设计与训练(第四版)[M],大连,大连理工大学出版社,2003.
[2]https://pan.baidu.com/s/17ZXphwqySNIsIgcGtYMjvg?pwd=lhwc