java中计算n的阶乘
时间: 2024-09-28 08:03:06 浏览: 41
在Java中,计算一个整数n的阶乘(factorial),可以使用递归或循环的方式。这里我们提供递归和非递归两种方法的代码:
**递归方法**:
```java
public class Main {
public static void main(String[] args) {
int n = 5; // 想要计算阶乘的数值
long factorial = calculateFactorial(n);
System.out.printf("The factorial of %d is %d%n", n, factorial);
}
public static long calculateFactorial(int num) {
if (num == 0 || num == 1) {
return 1;
} else {
return num * calculateFactorial(num - 1);
}
}
}
```
**非递归方法(使用循环)**:
```java
public class Main {
public static void main(String[] args) {
int n = 5;
long factorial = getNonRecursiveFactorial(n);
System.out.printf("The factorial of %d is %d%n", n, factorial);
}
public static long getNonRecursiveFactorial(int num) {
long fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}
}
```
在这两个例子中,`calculateFactorial`函数使用了递归,而`getNonRecursiveFactorial`则是一个循环版本,避免了递归带来的栈溢出风险。
阅读全文