Java中的递归阶乘方法

任何非负整数的阶乘基本上都是小于或等于该整数的所有整数的乘积。阶乘可以使用递归方法获得。

演示此过程的程序如下:

示例

public class Demo {
   public static long fact(long n) {
      if (n <= 1)
         return 1;
      else
         return n * fact(n - 1);
   }
   public static void main(String args[]) {
      System.out.println("The factorial of 6 is: " + fact(6));
      System.out.println("The factorial of 0 is: " + fact(0));
   }
}

输出结果

The factorial of 6 is: 720
The factorial of 0 is: 1

现在让我们了解上面的程序。

该方法fact()计算数字n的阶乘。如果n小于或等于1,则返回1。否则,它将递归调用自身并返回n * fact(n-1)。演示此代码段如下:

public static long fact(long n) {
   if (n <= 1)
      return 1;
   else
      return n * fact(n - 1);
}

在中main()fact()使用不同的值调用该方法。演示此代码段如下:

public static void main(String args[]) {
   System.out.println("The factorial of 6 is: " + fact(6));
   System.out.println("The factorial of 0 is: " + fact(0));
}