
在此程序中,您将学习使用Java中的for和while循环查找数字的阶乘。
正数的阶乘由下式n给出:
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
示例1:使用for循环查找数字的阶乘
public class Factorial {
public static void main(String[] args) {
int num = 10;
long factorial = 1;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}运行该程序时,输出为:
Factorial of 10 = 3628800
在此程序中,我们使用for循环遍历了1和给定数字num(10)之间的所有数字,每个数字的乘积直到num,并存储在变量factorial中。
我们使用long而不是int来存储阶乘的大结果。但是,它仍然不够大,不能存储更大数字的值(比如100的阶乘)
对于无法存储在long变量中的结果,我们使用在java.math库中声明的BigInteger变量。
示例2:使用BigInteger查找数字的阶乘
import java.math.BigInteger;
public class Factorial {
public static void main(String[] args) {
int num = 30;
BigInteger factorial = BigInteger.ONE;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.printf(" %d 的阶乘 = %d", num, factorial);
}
}运行该程序时,输出为:
30 的阶乘 = 265252859812191058636308480000000
这里,我们用BigInteger代替long存储阶乘。
由于*不能与一起使用BigInteger,因此我们将其multiply()用于该产品。另外,num应将其强制转换BigInteger为乘法。
因为*不能与BigInteger一起使用,所以我们对计算使用multiply()。另外,num应该被转换为BigInteger以进行乘法运算。
同样,我们也可以使用while循环来解决此问题。
示例3:使用while循环查找数字的阶乘
public class Factorial {
public static void main(String[] args) {
int num = 5, i = 1;
long factorial = 1;
while(i <= num)
{
factorial *= i;
i++;
}
System.out.printf("%d 的阶乘 = %d", num, factorial);
}
}运行该程序时,输出为:
5 的阶乘 = 120
在上面的程序中,与for循环不同,我们必须循环体内增加i的值。
尽管两个程序在技术上都是正确的,但在这种情况下最好使用for循环。这是因为迭代次数(最大为num)是已知的。