Kotlin Program to Find Factorial Using Recursion
fun factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1).Examples
How to Think About It
if to stop the recursion at this base case.Algorithm
Code
fun factorial(n: Int): Int {
return if (n <= 1) 1 else n * factorial(n - 1)
}
fun main() {
val number = 5
println("Factorial of $number is ${factorial(number)}")
}Dry Run
Let's trace factorial(5) through the code
Call factorial(5)
5 > 1, so return 5 * factorial(4)
Call factorial(4)
4 > 1, so return 4 * factorial(3)
Call factorial(3)
3 > 1, so return 3 * factorial(2)
Call factorial(2)
2 > 1, so return 2 * factorial(1)
Call factorial(1)
1 <= 1, return 1
Return values
factorial(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(1) | 1 |
| factorial(2) | 2 |
| factorial(3) | 6 |
| factorial(4) | 24 |
| factorial(5) | 120 |
Why This Works
Step 1: Base Case
The function stops calling itself when n is 1 or less, returning 1 to avoid infinite recursion.
Step 2: Recursive Call
For values greater than 1, the function calls itself with n - 1 to break the problem into smaller parts.
Step 3: Multiplying Results
Each call multiplies n by the factorial of n - 1, building the final factorial value step by step.
Alternative Approaches
fun factorialIterative(n: Int): Int {
var result = 1
for (i in 2..n) {
result *= i
}
return result
}
fun main() {
val number = 5
println("Factorial of $number is ${factorialIterative(number)}")
}tailrec fun factorialTailRec(n: Int, acc: Int = 1): Int { return if (n <= 1) acc else factorialTailRec(n - 1, n * acc) } fun main() { val number = 5 println("Factorial of $number is ${factorialTailRec(number)}") }
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself once per number down to 1, so it runs in linear time proportional to n.
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 constant space and is generally faster, while tail recursion can be optimized by Kotlin to avoid stack growth.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Simple code, small inputs |
| Iterative | O(n) | O(1) | Efficiency and large inputs |
| Tail Recursion | O(n) | O(1) | Safe recursion with compiler optimization |