Kotlin Tail-Recursive function: Calculate the power of a number
Kotlin Function: Exercise-17 with Solution
Write a Kotlin tail-recursive function to calculate the power of a number.
Sample Solution:
Kotlin Code:
tailrec fun power(base: Int, exponent: Int, result: Int = 1): Int {
if (exponent == 0) {
return result
}
return power(base, exponent - 1, result * base)
}
fun main() {
val base = 3
val exponent = 5
val result = power(base, exponent)
println("$base raised to the power of $exponent is: $result")
}
Sample Output:
3 raised to the power of 5 is: 243
Explanation:
In the above exercise -
- The "fibonacci()" function takes three parameters: n, which represents the position of the Fibonacci number to be calculated, a and b which are used to keep track of the previous two Fibonacci numbers.
- If n becomes 0, we have reached the desired position and return a, the current Fibonacci number.
- In each recursive call, we decrement n by 1 and calculate the next Fibonacci number by adding the previous two Fibonacci numbers (a + b). The current value of b becomes the new value of a, and the sum a + b becomes the new value of b.
- By using tail recursion, we make the recursive call directly without any additional computation.
- The recursive calls continue until the base case is reached and the final Fibonacci number is computed.
Kotlin Editor:
Previous: Calculate the nth Fibonacci.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/kotlin-exercises/recursion-function/kotlin-recursion-function-exercise-17.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics