正数
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("Factorial of %d = %d", num, factorial); } }
输出
Factorial of 30 = 265252859812191058636308480000000
这里,我们使用
BigInteger
变量阶乘代替
long
。
由于
*
不能与
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("Factorial of %d = %d", num, factorial); } }
输出
Factorial of 5 = 120
在上面的程序中,与 for 循环不同,我们必须在循环体内增加
i 的值。
虽然两个程序在技术上都是正确的,但在这种情况下最好使用 for 循环。这是因为迭代次数(最多
num)是已知的。
访问此页面以学习使用递归查找数字的阶乘。