w3resource

Kotlin Tail recursive function: Calculate factorial

Kotlin Function: Exercise-14 with Solution

Write a Kotlin tail recursive function that calculates the factorial of a given number.

Sample Solution:

Kotlin Code:

tailrec fun calculateFactorial(number: Int, accumulator: Long = 1): Long {
    return if (number == 0) {
        accumulator
    } else {
        calculateFactorial(number - 1, accumulator * number)
    }
}

fun main() {
    val number = 4
    val factorial = calculateFactorial(number)
    println("Factorial of $number: $factorial")
}

Sample Output:

Factorial of 4: 24

Explanation:

In the above exercise -

  • The "calculateFactorial()" function is a tail-recursive function. It takes two parameters: a number representing the number for which the factorial is calculated, and an accumulator stores the intermediate product.
  • Inside the function, there's a base case where if the number is 0, it returns the accumulator value, which holds the factorial result.
  • Otherwise, the function recursively calls itself with the number decreased by 1 and the accumulator multiplied by the current number.
  • By using tail recursion, the function can optimize recursive calls by using an accumulator variable and not creating additional stack frames. This prevents stack overflow errors with large inputs.
  • In the main function, a sample number is defined (5 in this case).
  • The "calculateFactorial()" function is called with the number, and the result is stored in the factorial variable.
  • Finally, the factorial value is printed to the console.

Kotlin Editor:


Previous: Sum of even numbers in a range.
Next: Sum of numbers from 1 to n.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.