Java中用for循环计算阶乘最常用,定义result=1,从1遍历到n逐次累乘;while循环同理,需手动控制计数器。

Java 中用循环计算阶乘,核心是用 for 或 while 循环逐步累乘从 1 到 n 的所有整数。
用 for 循环实现阶乘
这是最常用、最直观的方式。定义一个变量(如 result)初始为 1,然后从 1 遍历到 n,每次乘上当前数字。
示例代码:
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("阶乘不能计算负数");
}
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
- n 为 0 时,循环不执行,直接返回 1(符合数学定义:0! = 1)
- 使用
long类型可支持到约 20!;超过会溢出,如需更大值需改用BigInteger - 注意判断负数输入,避免无效计算
用 while 循环实现阶乘
逻辑和 for 循环一致,只是把循环变量的初始化、条件判断、递增拆开写,更显式控制流程。
立即学习“Java免费学习笔记(深入)”;
public static long factorialWhile(int n) {
if (n < 0) {
throw new IllegalArgumentException("阶乘不能计算负数");
}
long result = 1;
int i = 1;
while (i <= n) {
result *= i;
i++;
}
return result;
}
- 适合想清晰看到每一步变化或需要中途加调试逻辑的场景
- 务必在循环体内更新计数器(如
i++),否则容易陷入死循环
处理大数:用 BigInteger 避免溢出
当 n > 20 时,long 不够用。Java 提供 java.math.BigInteger 支持任意精度整数运算。
import java.math.BigInteger;
public static BigInteger factorialBig(int n) {
if (n < 0) {
throw new IllegalArgumentException("阶乘不能计算负数");
}
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
-
BigInteger.ONE是常量,代表 1;不能用new BigInteger("1")重复创建 - 所有运算都用方法调用(如
multiply),不可用*运算符 - 返回类型必须是
BigInteger,调用处注意接收和输出格式
简单测试与调用
可在 main 方法中验证结果是否正确:
public static void main(String[] args) {
System.out.println(factorial(5)); // 输出 120
System.out.println(factorialWhile(0)); // 输出 1
System.out.println(factorialBig(50)); // 输出超长精确结果
}
- 建议从小数值(如 0、1、5)开始测试,再逐步增大
- 对比已知结果(如 5! = 120)快速确认逻辑无误
- 若用于教学或练习,可加打印语句观察每次乘法过程


















