在 java 中使用 while 循环计算阶乘,核心做法是初始化一个累乘变量为 1 和一个计数器为 1,然后在计数器小于等于目标数的条件下持续将计数器值乘入累乘变量并递增计数器。对于输入 n,若 n 为 0 或 1,结果直接为 1;若 n 大于 1,循环结束后累乘变量即为 n!。需注意整数溢出问题,当 n >= 13 时 long 类型也会溢出,通常仅适用于小数值计算。

while 循环控制阶乘计算的流程是怎样的
while 循环通过判断条件决定是否继续执行乘法操作。初始时 multiplier 设为 1,counter 设为 1。只要 counter

public class FactorialWhile {
public static void main(String[] args) {
int n = 5;
long result = 1;
int counter = 1;
while (counter <= n) {
result *= counter;
counter++;
}
System.out.println(n + "! = " + result);
}
}
运行上述代码,输入 n=5,预期输出为:5! = 120。验证过程:counter=1 时 result=1*1=1;counter=2 时 result=1*2=2;counter=3 时 result=2*3=6;counter=4 时 result=6*4=24;counter=5 时 result=24*5=120;counter=6 时循环结束。最终结果为 120,符合 5! 的定义。
立即学习“Java免费学习笔记(深入)”;
如何处理边界情况如 n=0 或负数输入
数学上 0! 定义为 1,而负数没有阶乘定义。在 while 循环实现中,若 n=0,初始条件 counter=1

public class FactorialWithValidation {
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Negative input not allowed");
}
long result = 1;
int counter = 1;
while (counter <= n) {
result *= counter;
counter++;
}
return result;
}
public static void main(String[] args) {
System.out.println(factorial(0)); // 输出 1
System.out.println(factorial(5)); // 输出 120
}
}
运行上述代码,factorial(0) 返回 1,factorial(5) 返回 120。若调用 factorial(-1),则抛出 IllegalArgumentException。这确保了只有非负整数被处理,符合阶乘的数学定义。对于 n=0,循环条件 counter=1
当输入 n=13 时会发生什么具体现象
当输入 n=13 时,由于 13! = 6,227,020,800,超过了 long 类型的最大值 9,223,372,036,854,775,807 吗?实际上 13! = 6,227,020,800 仍在 long 范围内(long 最大约 9.2e18),但 20! 才接近 long 上限。然而,13! 实际值为 6,227,020,800,而 long 能容纳。但若使用 int 类型,int 最大为 2,147,483,647,13! 已超出 int 范围,会导致溢出。在上面的代码中使用 long,n=13 时结果正确。但若 n=20,20! = 2,432,902,008,176,640,000,仍小于 long 最大值,但 n=21 时 21! 会溢出。因此,使用 long 时,n 最大支持到 20。若需更大值,应使用 BigInteger。
public class FactorialLongLimit {
public static void main(String[] args) {
int n = 20;
long result = 1;
int counter = 1;
while (counter <= n) {
result *= counter;
counter++;
}
System.out.println(n + "! = " + result);
}
}
运行上述代码,n=20 时输出 20! = 2432902008176640000。若改为 n=21,结果会因溢出而错误。这展示了 long 类型的限制,提醒开发者在需要更大阶乘时使用 BigInteger 或其他大数库。


















