To create a recursive function to calculate the factorial of a number in Java, you can use a recursive function that calls itself with the input number minus one until it reaches the base case, which is when the input number is equal to 1
.
Here is an example of how you can create a recursive function to calculate the factorial of a number in Java:
public static long factorial(int n) { if (n == 1) { return 1; } return n * factorial(n - 1); }
In this example, the factorial
function is defined with a single int
parameter n
. If n
is equal to 1
, the function returns 1
as the base case. Otherwise, the function returns n
multiplied by the result of calling the factorial
function with n - 1
.
You can call the factorial
function with a number to calculate its factorial, as shown in the following example:
int n = 5; long result = factorial(n); System.out.println(result); // prints "120"
In this example, the factorial
function is called with the value 5
, and the result is printed to the console. The output will be 120
, which is the factorial of 5
.
Keep in mind that recursive functions can be computationally expensive, especially for large input values, as they require additional function calls and memory allocation for each recursive step. In such cases, it may be more efficient to use an iterative solution to calculate the factorial of a number.