Kotlin Tail recursive function: Calculate factorial
Write a Kotlin tail recursive function that calculates the factorial of a given number.
Pre-Knowledge (Before You Start!)
Before solving this exercise, you should be familiar with the following concepts:
- Factorial: The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It's commonly represented as n!.
- Tail Recursion: A recursive function is called tail-recursive when the recursive call is the last operation in the function. Tail recursion is more efficient because it avoids creating additional stack frames for each call.
- Accumulator: An accumulator is a variable that stores intermediate results, and it's often used in recursive functions to accumulate the result of the computation as the recursion progresses.
- Base Case: A base case is the condition that stops the recursion. For factorial, when the number is 0, the factorial is 1 (by definition), and the recursion stops.
- Recursive Case: In this case, we reduce the number by 1 and multiply the accumulator by the current number in each recursive call.
Hints (Try Before Looking at the Solution!)
Here are some hints to help you solve the problem:
- Hint 1: Start by writing the basic recursive function to calculate the factorial of a number, without worrying about tail recursion.
- Hint 2: Add an accumulator parameter to your function. This parameter will hold the intermediate product and is updated with each recursive call.
- Hint 3: In each recursive call, decrease the number by 1 and multiply the accumulator by the current number. Continue this until the number becomes 0.
- Hint 4: Make sure that when the number is 0, the function returns the accumulator, which will have accumulated the factorial result.
- Hint 5: Use the tailrec keyword in Kotlin to optimize the recursion and prevent stack overflow errors with large inputs.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics