题目
求∑(1,20)n!(即求1!+2!+3!+…+20!)
思路
先写个函数求阶乘,可以递归也可以循环,我更喜欢循环,时间复杂度小,求和的变量不能定义成int整型,因为20的阶乘的结果位数大,int整型位数不够,需要声明为long double变量
解答
#include <stdio.h>
//阶乘函数
long double Factorial(long double n)
{
//规定0的阶乘为1
if (n == 0)
{
return 1.0;
}
long double temp = 1.0;
for (int i = 1; i <= n; i++)
{
temp = temp * i;
}
return temp;
}
//求和
void sum(int n)
{
long double result = 0;
//题目规定从1开始
for (int i = 1; i <= n; i++)
{
result = result + Factorial(i);
printf("%d!", i);
if (i != n)
{
printf("+");
}
}
printf("=%f", result);
}
int main()
{
sum(20);
}