C Exercise 25
100 Classic C Language Examples
**Problem:** Find the sum of 1 + 2! + 3! + ... + 20!.
**Analysis:** This program simply changes accumulation into multiplication.
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
<
stdio.h
// Function to calculate factorial
unsigned
long
long
factorial
(
int
n
)
{
unsigned
long
long
result
=
1
;
for
(
int
i
=
1
;
i
<=
n
;
i
++
)
{
result
*=
i
;
}
return
result
;
}
int
main
(
)
{
unsigned
long
long
sum
=
0
;
// Calculate 1 + 2! + 3! + ... + 20!
for
(
int
i
=
1
;
i
<=
20
;
i
++
)
{
sum
+=
factorial
(
i
)
;
}
// Output result
printf
(
"
The sum of 1 + 2! + 3! + ... + 20! is: %llu
\
n
"
,
sum
)
;
return
0
;
}
The output of the above example is:
1 + 2! + 3! + ... + 20!的和是: 2561327494111820313
Code Analysis
- Header File: Include the necessary header files
stdio.h. - Factorial function:
unsigned long long factorial(int n)The function is used to compute a given integern's factorial, with a return type ofunsigned long longto handle larger values. - Initialization
resultis 1. - Use
forThe loop multiplies from 1 up ton.
- Main function:
- define
suma variable to accumulate the sum of all factorials, of typeunsigned long longto handle larger values. - Use
fora loop to compute the factorials from 1 to 20 and accumulate the results intosum. - Use
printfthe function outputs the final result.