p5739 【深基7.例7】计算阶乘
时间: 2023-04-26 11:05:14 浏览: 81
题目描述:
输入一个正整数n,输出n的阶乘。
输入格式:
一个正整数n。
输出格式:
一个正整数,即n的阶乘。
输入样例:
5
输出样例:
120
算法思路:
阶乘的定义是:n!=n×(n−1)×(n−2)×...×2×1。
因此,我们可以使用循环来计算n的阶乘。具体来说,从1到n依次枚举每个数,将它们相乘即可。
时间复杂度:O(n)
C++代码:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int ans = 1;
for (int i = 1; i <= n; i++)
{
ans *= i;
}
cout << ans << endl;
return ;
}
Python代码:
n = int(input())
ans = 1
for i in range(1, n+1):
ans *= i
print(ans)
相关问题
7-2 求阶乘factorial.java
好的,关于计算阶乘的问题,我可以为您提供以下 Java 代码:
```java
import java.math.BigInteger;
public class factorial {
public static BigInteger factorial(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
public static void main(String[] args) {
int n = 7;
BigInteger result = factorial(n);
System.out.println(n + "! = " + result);
}
}
```
以上代码可以计算出 7 的阶乘,输出结果为 5040。如果您想计算其他数的阶乘,只需要修改代码中的 n 的值即可。希望我的回答能够帮到您。
C语言 计算阶乘 5!+7!+10!
下面是使用C语言计算阶乘并求和的代码:
```c
#include <stdio.h>
int main() {
int i, j;
int sum = 0;
int n[] = {5, 7, 10};
for (i = 0; i < 3; i++) {
int factorial = 1;
for (j = 1; j <= n[i]; j++) {
factorial *= j;
}
sum += factorial;
}
printf("5! + 7! + 10! = %d\n", sum);
return 0;
}
```
输出结果为:5! + 7! + 10! = 40454740
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)