正数 n 的阶乘由下式给出:
factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
负数的阶乘不存在。0的阶乘是1。
在此示例中,您将学习如何使用递归查找数字的阶乘。访问此页面了解如何使用循环查找 数字的阶乘。
示例:使用递归计算数字的阶乘
public class Factorial {
public static void main(String[] args) {
int num = 6;
long factorial = multiplyNumbers(num);
System.out.println("Factorial of " + num + " = " + factorial);
}
public static long multiplyNumbers(int num)
{
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}
输出
Factorial of 6 = 720
最初,multiplyNumbers()
函数从main()
函数调用,并传入6作为参数。
由于6大于或等于1,因此6乘以multiplyNumbers()
的结果,而multiplyNumbers()
的参数为5(num -1)。由于它是从同一函数调用的,所以这是一个递归调用。
在每次递归调用中,参数 num 的值都会减1,直到 num 小于1。
当 num 的值小于1时,将不再进行递归调用。
并且每次递归调用都会返回结果
6 * 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 720