java如何表示阶乘
Java 表示阶乘的方法
使用循环实现阶乘
通过循环结构(如 for 或 while)计算阶乘是最基础的方法。以下是示例代码:
public static long factorialWithLoop(int n) {
if (n < 0) throw new IllegalArgumentException("n must be non-negative");
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
- 参数校验:输入
n必须为非负数,否则抛出异常。 - 循环累乘:从 2 开始逐步累乘到
n,初始值为 1(因为 0! 和 1! 均为 1)。
使用递归实现阶乘
递归方法利用阶乘的数学定义(n! = n × (n-1)!)直接实现:
public static long factorialWithRecursion(int n) {
if (n < 0) throw new IllegalArgumentException("n must be non-negative");
return n <= 1 ? 1 : n * factorialWithRecursion(n - 1);
}
- 基线条件:当
n为 0 或 1 时返回 1。 - 递归调用:将问题分解为
n乘以(n-1)!的子问题。
处理大数阶乘
当 n 较大时(如 n > 20),long 类型会溢出,需使用 BigInteger:

import java.math.BigInteger;
public static BigInteger factorialWithBigInteger(int n) {
if (n < 0) throw new IllegalArgumentException("n must be non-negative");
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
- 大数运算:
BigInteger支持任意精度的整数运算,避免溢出问题。
注意事项
- 性能考量:递归方式代码简洁,但可能引发栈溢出(如
n极大时),循环更安全。 - 输入范围:
long类型最大支持20!(值为 2432902008176640000),BigInteger无此限制。
示例调用
public static void main(String[] args) {
System.out.println(factorialWithLoop(5)); // 输出 120
System.out.println(factorialWithRecursion(5)); // 输出 120
System.out.println(factorialWithBigInteger(50)); // 输出 30414093201713378043612608166064768844377641568960512000000000000
}





