0
0
KotlinProgramBeginner · 2 min read

Kotlin Program to Find Factorial Using Recursion

You can find the factorial of a number in Kotlin using recursion by defining a function like fun factorial(n: Int): Int = if (n <= 1) 1 else n * factorial(n - 1).
📋

Examples

Input0
OutputFactorial of 0 is 1
Input5
OutputFactorial of 5 is 120
Input1
OutputFactorial of 1 is 1
🧠

How to Think About It

To calculate factorial recursively, think of the problem as multiplying the number by the factorial of the number just before it. Keep doing this until you reach 1 or 0, where the factorial is 1 by definition. Use if to stop the recursion at this base case.
📐

Algorithm

1
Get the input number n
2
Check if n is less than or equal to 1
3
If yes, return 1 as factorial
4
Otherwise, return n multiplied by factorial of n minus 1
💻

Code

kotlin
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)}")
}
Output
Factorial of 5 is 120
🔍

Dry Run

Let's trace factorial(5) through the code

1

Call factorial(5)

5 > 1, so return 5 * factorial(4)

2

Call factorial(4)

4 > 1, so return 4 * factorial(3)

3

Call factorial(3)

3 > 1, so return 3 * factorial(2)

4

Call factorial(2)

2 > 1, so return 2 * factorial(1)

5

Call factorial(1)

1 <= 1, return 1

6

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

CallReturn 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

Iterative approach
kotlin
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)}")
}
This uses a loop instead of recursion, which can be more efficient and avoids stack overflow for large numbers.
Using tail recursion
kotlin
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)}")
}
Tail recursion optimizes recursive calls to avoid growing the call stack, making it safer for large inputs.

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.

ApproachTimeSpaceBest For
RecursiveO(n)O(n)Simple code, small inputs
IterativeO(n)O(1)Efficiency and large inputs
Tail RecursionO(n)O(1)Safe recursion with compiler optimization
💡
Always include a base case in recursion to stop infinite calls.
⚠️
Forgetting the base case causes the function to call itself forever and crash.