分别用迭代法和递归法编写一个求 n!的函数,来求 1!+2!+3!+…+10!的值
时间: 2024-02-06 19:02:57 浏览: 69
以下是分别用迭代法和递归法编写一个求n!的函数,并计算1!+2!+3!+…+10!的值的代码:
```c
#include <stdio.h>
// 递归法求n!
int Facl_recursion(int n) {
if (n < 2) {
return 1;
} else {
return n * Facl_recursion(n - 1);
}
}
// 迭代法求n!
int Facl_iteration(int n) {
int i, ret = 1;
for (i = 1; i <= n; i++) {
ret *= i;
}
return ret;
}
int main() {
int i, sum = 0;
for (i = 1; i <= 10; i++) {
sum += Facl_iteration(i);
}
printf("1!+2!+3!+...+10!=%d\n", sum);
sum = 0;
for (i = 1; i <= 10; i++) {
sum += Facl_recursion(i);
}
printf("1!+2!+3!+...+10!=%d\n", sum);
return 0;
}
```
相关问题
c语言分别用迭代法和递归法编写一个求n!的函数 来求1!+2!+3!+…+10!的值
迭代法实现n!的函数:
```c
#include <stdio.h>
int factorial_iterative(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += factorial_iterative(i);
}
printf("1!+2!+3!+...+10!=%d\n", sum);
return 0;
}
```
递归法实现n!的函数:
```c
#include <stdio.h>
int factorial_recursive(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial_recursive(n - 1);
}
}
int main() {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += factorial_recursive(i);
}
printf("1!+2!+3!+...+10!=%d\n", sum);
return 0;
}
```
分别用迭代法和递归法编写一个求 n!的函数,来求 1!+2!+3!+…+10!的值。
以下是分别用迭代法和递归法编写一个求 n!的函数的例子,以及求1!+2!+3!+…+10!的值的代码:
1. 迭代法求n!的函数
```python
def factorial_iterative(n):
result = 1
for i in range(1, n+1):
result *= i
return result
```
2. 递归法求n!的函数
```python
def factorial_recursive(n):
if n == 1:
return 1
else:
return n * factorial_recursive(n-1)
```
3. 求1!+2!+3!+…+10!的值
```python
sum = 0
for i in range(1, 11):
sum += factorial_iterative(i)
print(sum)
```
阅读全文