question
Please calculate the sum of the factorials of N numbers
think
先把问题分为两个部分
1. The factorial of N
那么N的阶乘应该是从1乘到N
也就是说for循环
int sum=1;
for (int i = 1; i <= n; ++i)
{
sum2 = sum2 * i;
}
2. Add N factorials
那么N个数相加也应写一个for循环
for (int i = 1; i <= n; ++i)
{
sum1 = sum2 +i ;
}
3. How to nest
先来思考结构:
必然是要有两个for,一个相加,一个求阶乘
那么先来列举几个
当n=2:
那么就是1!+2!,直接写代码就该是
//The first time is 1!
int sum=1;
for (int i = 1; i <= 1; ++i)
{
sum2 = sum2 * i;
}
//The second time is 2!
int sum=1;
for (int i = 1; i <= 2; ++i)
{ sum2 = sum2 * i; } Then add the sum2 of the two. Then just add up the separate codes, but it should be noted that the sum2 here should be reset to 1 every time, because the calculation is the factorial of the inner layer, and the value of sum2 should be added to the sum1 every time, that is, for ( int i = 1; i <= n; ++i) { sum2=1 for(){}; sum1 = sum2 +i ; }
the code
#include<stdio.h>
int main()
{
long long a,sum1=0,sum2=1;
scanf("%lld", &a);
for (int i = 1; i <= a; ++i)
{
sum2 = 1;
for (int j = 1; j <= i; ++j)
{
sum2 = sum2 * j;
}
sum1 = sum1 + sum2;
}
printf("%lld", sum1);
return 0;
}