Java Program to Find Factorial Using Recursion
int factorial(int n) { return (n == 0) ? 1 : n * factorial(n - 1); } which calls itself until it reaches zero.Examples
How to Think About It
Algorithm
Code
public class Factorial { public static int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } public static void main(String[] args) { int number = 5; System.out.println("Factorial of " + number + " is " + factorial(number)); } }
Dry Run
Let's trace factorial(5) through the code
Call factorial(5)
Since 5 != 0, return 5 * factorial(4)
Call factorial(4)
Since 4 != 0, return 4 * factorial(3)
Call factorial(3)
Since 3 != 0, return 3 * factorial(2)
Call factorial(2)
Since 2 != 0, return 2 * factorial(1)
Call factorial(1)
Since 1 != 0, return 1 * factorial(0)
Call factorial(0)
Since 0 == 0, return 1
Return values back up
factorial(1) = 1 * 1 = 1 factorial(2) = 2 * 1 = 2 factorial(3) = 3 * 2 = 6 factorial(4) = 4 * 6 = 24 factorial(5) = 5 * 24 = 120
| Call | Return Value |
|---|---|
| factorial(0) | 1 |
| factorial(1) | 1 |
| factorial(2) | 2 |
| factorial(3) | 6 |
| factorial(4) | 24 |
| factorial(5) | 120 |
Why This Works
Step 1: Base Case
The recursion stops when n == 0, returning 1 because factorial of zero is defined as 1.
Step 2: Recursive Call
For any other number, the function calls itself with n - 1, breaking the problem into smaller parts.
Step 3: Multiplication
Each call multiplies the current number n by the factorial of n - 1, building the final result as the calls return.
Alternative Approaches
public class Factorial { public static int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } public static void main(String[] args) { int number = 5; System.out.println("Factorial of " + number + " is " + factorial(number)); } }
import java.util.stream.IntStream; public class Factorial { public static int factorial(int n) { return IntStream.rangeClosed(1, n).reduce(1, (a, b) -> a * b); } public static void main(String[] args) { int number = 5; System.out.println("Factorial of " + number + " is " + factorial(number)); } }
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself n times, so the time grows linearly with the input number.
Space Complexity
Each recursive call adds a new layer to the call stack, so space used is proportional to n.
Which Approach is Fastest?
The iterative approach uses O(1) space and is generally faster due to no overhead of recursive calls, but recursion is more elegant and easier to understand.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Clear logic, small inputs |
| Iterative | O(n) | O(1) | Large inputs, performance |
| Streams | O(n) | O(1) | Functional style, concise code |