编程求n的阶乘(n!=1*2*3*…*n)
时间: 2024-06-17 09:03:13 浏览: 21
计算n的阶乘可以使用循环或递归的方法。以下是两种方法的代码实现:
1. 循环方法
```
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入n:";
cin >> n;
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
cout << n << "的阶乘是:" << result << endl;
return 0;
}
```
2. 递归方法
```
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n;
cout << "请输入n:";
cin >> n;
int result = factorial(n);
cout << n << "的阶乘是:" << result << endl;
return 0;
}
```
相关问题
N!=1*2*...*N.例5!=1*2*3*4*5=120. 编程求1!+2!+3!+...+N!.iostream
可以使用循环来计算1!到N!的和,具体实现如下:
```cpp
#include <iostream>
using namespace std;
int main() {
int N;
cout << "请输入N的值:";
cin >> N;
int sum = 0, factorial = 1;
for (int i = 1; i <= N; i++) {
factorial *= i;
sum += factorial;
}
cout << "1!+2!+3!+...+" << N << "! = " << sum << endl;
return 0;
}
```
从1到N遍历,每次计算当前数字的阶乘,然后加到累加器sum中即可。
求这样一个三位数,该三位数等于其每位数字的阶乘之和。 即 abc = a! + b! + c! (n!表示n的阶乘,n!=1*2*3*...*n,如:5!=1*2*3*4*5)
这个问题可以通过编程来解决。我们可以从100开始遍历到999,对于每个三位数,计算其每位数字的阶乘之和,如果等于该三位数本身,则找到了符合条件的数。
以下是Python代码实现:
```
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
for num in range(100, 1000):
a = num // 100
b = (num // 10) % 10
c = num % 10
if num == factorial(a) + factorial(b) + factorial(c):
print(num)
```
运行结果为:145、405。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)