Kotlin – Find factorial of a number using recursion

Find Factorial of a Number using Recursion in Kotlin

In this tutorial, you will learn how to calculate the factorial of a given number using recursion in Kotlin.

You can calculate the factorial of a number using recursion in Kotlin. Recursion involves breaking down a problem into smaller instances of the same problem. For factorial calculation, the base case is when the number is 0 or 1, and for other numbers, the function calls itself with a smaller number and multiplies it with the current number.

Example

Calculating Factorial using Recursion

We’ll start with an example of calculating the factorial of a number using recursion:

Factorial of a number is the product of all positive integers from 1 to that number.

In this example, the calculateFactorialRecursive() function calculates the factorial of the given number using recursion.

Kotlin Program

// Function to calculate factorial using recursion
fun calculateFactorialRecursive(number: Int): Long {
    return if (number == 0 || number == 1) {
        1
    } else {
        number.toLong() * calculateFactorialRecursive(number - 1)
    }
}

fun main() {
    val number = 5
    val result = calculateFactorialRecursive(number)
    println("Factorial of $number is: $result")
}

Output

Factorial of 5 is: 120

Summary

In this Kotlin Tutorial, we learned how to find the factorial of a given number using recursion in Kotlin, with the help of example programs.