编程求“1! +2! +·.·+n!”,用单循环实现
时间: 2023-10-02 09:05:31 浏览: 87
可以使用一个循环和一个变量来实现求和,具体实现如下:
```
int n = 5;
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
cout << result << endl;
```
输出结果为 5! = 120。
相关问题
编程求1!+2!+3!+...+n!,用单循环实现
```c
# include <stdio.h>
int main(void) {
int n = 0;
int i = 0;
int m = 1;
int sum=0;
printf("请输入n的值:");
scanf("%d", &n);
for (i=1; i<=n; ++i) {
m = m * i;
sum = sum + m;
}
printf ("sum = %d\n", sum);
return 0;
}
```
编程求1!+2!+3!+4!+...+n!的值。分别用单循环和双重循环做。 #测试:
好的,我来为您解答这个问题。
单循环实现:
def factorial(n):
res = 1
for i in range(1, n+1):
res *= i
return res
def sum_factorial(n):
res = 0
for i in range(1, n+1):
res += factorial(i)
return res
print(sum_factorial(5)) # 输出153
双重循环实现:
def factorial(n):
res = 1
for i in range(1, n+1):
res *= i
return res
def sum_factorial(n):
res = 0
for i in range(1, n+1):
temp = 1
for j in range(1, i+1):
temp *= j
res += temp
return res
print(sum_factorial(5)) # 输出153
两种方法的时间复杂度都是O(n^2),但是单循环的实现更加简洁。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)