Difficulty: Easy to Moderate
Topics: Recursion, Iterative Algorithms, Mathematics
Applications: Used in combinatorics, probability, and programming challenges.
Imagine you have a set of building blocks, and you want to know how many unique structures you can create by stacking them in every possible arrangement. This is the idea behind factorials in mathematics.
The factorial of a number n
, written as n!
(n factorial), represents the total number of ways you can arrange a set of n
distinct objects.
For n = 3
(3 blocks):
Recursion involves solving a problem by breaking it down into smaller, similar subproblems. A recursive function calls itself within its body but with a smaller input until it reaches a base case (a condition where the function stops calling itself).
To calculate n!
using recursion:
n
by the factorial of n-1
.n
reaches the base case, where n = 1
or n = 0
.For these cases:
5!
Recursively:5! = 5 × 4!
4! = 4 × 3!
3! = 3 × 2!
2! = 2 × 1!
1! = 1
(Base case reached)Result:
Input:
n = 5
Execution:
factorial_recursive(5)
Output:
120
n = 0
)Input:
n = 0
Execution:
factorial_recursive(0)
Output:
1
n = 1
)Input:
n = 1
Execution:
factorial_recursive(1)
Output:
1
Input:
n = 10
Execution:
factorial_recursive(10)
Output:
3628800
Loading component...
Loading component...
INPUT: N =5
OUTPUT: 120
public static void main(String[] args) {
int num = 5;
System.out.println("Factorial of " + num + " is " + factorial(5));
} // Function End
public static int factorial(int n){
if(n == 0 || n == 1){
return 1;
}//If End
int ans = n * factorial(n-1);
return ans;
}//function end
Utility Function is not required.