Java script求n的阶乘
时间: 2023-09-09 13:13:12 浏览: 45
以下是使用递归方法实现的JavaScript代码:
```javascript
function factorial(n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(5)); // 输出 120
```
如果n等于1或0,则返回1。否则,返回n乘以n-1的阶乘。递归函数在n为1时停止。
相关问题
java求n的阶乘代码
Java求n的阶乘的代码可以使用循环或递归的方式实现。下面给出两种不同的代码示例:
代码示例1(使用循环):
```java
import java.util.Scanner;
public class Main {
public static int factorial(int x){
int product = 1;
for (int i = 1; i <= x ; i++) {
product = product * i;
}
return product;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("请输入一个数字:");
int n = s.nextInt();
System.out.println(n + "的阶乘为:" + factorial(n));
}
}
```
代码示例2(使用递归):
```java
import java.util.Scanner;
public class Main {
public static int factorial(int x){
if(x==1){
return 1;
}
return x * factorial(x-1);
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("请输入一个数字:");
int n = s.nextInt();
System.out.println(n + "的阶乘为:" + factorial(n));
}
}
```
请注意,在输入数字后,程序将会输出该数字的阶乘结果。
java求n的阶乘for循环
以下是Java中使用for循环求n的阶乘的代码:
```java
public class Factorial {
public static void main(String[] args) {
int n = 5; // 求5的阶乘
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println(n + "的阶乘是:" + result);
}
}
```
输出结果为:
```
5的阶乘是:120
```
需要求其他数的阶乘,只需将代码中的n改为其他数字即可。