How to calculate the factorial of n using a recursion a…

To find the factorial of n using Java’s recursive algorithm, you can use the following code:

public class Factorial {
    public static void main(String[] args) {
        int n = 5;
        int result = factorial(n);
        System.out.println(n + "的阶乘是:" + result);
    }

    public static int factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
}

In the code above, we have defined a factorial method that takes an integer n as a parameter and calculates the factorial of n using recursion. The base case of the recursion is when n equals 0, in which case it returns 1. Otherwise, the factorial method is recursively called to calculate the factorial of n-1, which is then multiplied by n and returned as the result. In the main method, we call the factorial method to calculate the factorial of 5 and print out the result. The output shows that the factorial of 5 is 120.

bannerAds