Unlocking the Power of Recursion: Calculating Factorials
The Factorial Formula
Before we dive into the code, let’s review the basic formula for calculating the factorial of a number. For any positive integer n, the factorial is represented as n! and is calculated as:
n! = n × (n-1) × (n-2) ×... × 1
For instance, the factorial of 6 (6!) would be:
6! = 6 × 5 × 4 × 3 × 2 × 1 = 720
The Recursive Approach
Now, let’s create a Java method that uses recursion to calculate the factorial of a given number. We’ll define a method called multiplyNumbers() that takes an integer num as an argument.
public class FactorialExample {
public static void main(String[] args) {
int number = 6; // number to calculate factorial
long factorial = multiplyNumbers(number);
System.out.println("Factorial of " + number + " = " + factorial);
}
public static long multiplyNumbers(int num) {
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}
How Recursion Works
When we call multiplyNumbers() from the main() function, it triggers a series of recursive calls. Each call reduces the value of num by 1 until it reaches 0. At that point, the method returns 1, and the recursive calls unwind, multiplying the results together to produce the final factorial value.
The Result
Running this code, we get:
Factorial of 6 = 720
As expected, the factorial of 6 is indeed 720! By leveraging recursion, we’ve created a concise and efficient method for calculating factorials.