Skip to content

Latest commit

 

History

History
55 lines (38 loc) · 1.64 KB

File metadata and controls

55 lines (38 loc) · 1.64 KB

Java 程序:使用递归查找数字的阶乘

原文: https://www.programiz.com/java-programming/examples/factorial-recursion

在此程序中,您将学习使用 Java 中的递归函数查找并显示数字的阶乘。

正数 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

最初,从main()函数调用multiplyNumbers(),并将 6 作为参数传递。

由于 6 大于或等于 1,因此将 6 与multiplyNumbers()的结果相乘,其中传递了 5(num - 1)。 由于是从同一函数调用的,因此它是递归调用。

在每个递归调用中,参数num的值减小 1,直到num小于 1。

num的值小于 1 时,将没有递归调用。

每个递归调用都会返回给我们:

6 * 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 720