1 普通方式
package org.test;
public class FactorialExample {
public static long factorialIterative(int n) {
// 处理边界情况
if (n < 0) {
throw new IllegalArgumentException("阶乘只能计算非负整数");
}
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int number = 5;
long result = factorialIterative(number);
System.out.println("使用循环计算 " + number + "! = " + result);
}
}
2 递归方式
package org.test;
public class FactorialExample {
public static long factorialRecursive(int n) {
// 处理边界情况
if (n < 0) {
throw new IllegalArgumentException("阶乘只能计算非负整数");
}
// 基本情况:0! = 1
if (n == 0) {
return 1;
}
// 递归调用
return n * factorialRecursive(n - 1);
}
public static void main(String[] args) {
int number = 5;
long result = factorialRecursive(number);
System.out.println("使用递归计算 " + number + "! = " + result);
}
}