(c language 1) factorial summation

input format

Find the value of Sn=1!+2!+3!+4!+5!+…+n!, where n is a number (n does not exceed 20).

input format

n

output format

The value of Sn

sample input

5

sample output

153

answer

Then go directly to the solution

#include<stdio.h>
int main()
{
    int n,a=1;
    long long sum=0,m=1; //为这是阶乘求和,一般的int 类型可能就不够,因此我们利用long long int 类型
    scanf("%d",&n); //输入需要乘到多少的阶乘
    for(a=1;a<=n;a++) //利用循环加1
    {
        m=a*m;  //一个循环利用上一个阶乘的结果加1直接乘
        sum=sum+m; //阶乘求和
    }
    printf("%lld",sum); //输出和
	return 0;
}

analyze

The previous int is generally used to control the loop, and the quantitative n is for the input of scanf.

Let's talk about this cycle first,

for(a=1;a<=n;a++)
    {
        m=a*m;
        sum=sum+m;
    }

We have defined the value of a and output the value of n at the beginning

This cycle is to make the value of m can be multiplied (a++) to achieve the effect of factorial. 

sum is also in the loop, so every loop can add the sum of the previous number

Until the value of a and n are the same, it just realizes the factorial sum and then exits the loop

The reason why I used it earlier 

long long sum=0,m=1;

It is because I believe that many children's shoes also want to use simple "%d" to output sum at the beginning

but the result is

 Obviously, the front test points can pass, but the latter ones cannot. Many children's shoes probably guess that there is a problem with the later output.

It suddenly occurred to me that if n is equal to 20, then this value must be very large

The maximum value of long long : 9223372036854775807 The minimum value of
long long : -9223372036854775808

So I only defined sum with long long at the beginning

But the result is as above, still the same error is reported, and there is an m, the natural value of m must be quite large

So I used long long to define both sum and m

Finally this output

printf("%lld",sum);

Note that long long is used to define, the output "%lld" is not the number 11, but the lowercase L.

This question comes from the question number 1014 of C Language Network

Guess you like

Origin blog.csdn.net/a871923942/article/details/130613049