在Java中,我们可以使用递归或循环来计算阶乘。以下是两种方法的代码示例:
- 使用递归计算阶乘:
public class Factorial {
public static void main(String[] args) {
int n = 5;
long result = factorial(n);
System.out.println("阶乘 " + n + " 的结果是: " + result);
}
public static long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
- 使用循环计算阶乘:
public class Factorial {
public static void main(String[] args) {
int n = 5;
long result = factorial(n);
System.out.println("阶乘 " + n + " 的结果是: " + result);
}
public static long factorial(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}