用php非递归写n的阶乘
时间: 2024-05-11 21:15:09 浏览: 10
可以使用如下代码实现:
```
function factorial($n) {
$result = 1;
for ($i = 1; $i <= $n; $i++) {
$result *= $i;
}
return $result;
}
echo factorial(5); // 输出 120
```
请注意,如果您需要计算非常大的阶乘,可能需要使用高精度计算库。
相关问题
用java递归写N的阶乘
public class Factorial {
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
int n = 5;
int result = factorial(n);
System.out.println(n + "的阶乘是: " + result);
}
}
非递归求n的阶乘
可以使用循环来非递归地求解n的阶乘。具体实现如下:
```c++
#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;
}
```
在上面的代码中,我们使用了一个循环,从1到n依次累乘,最终得到n的阶乘。
相关推荐
![](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)