w3resource

Kotlin Tail-Recursive function: Calculate the nth Fibonacci

Kotlin Function: Exercise-16 with Solution

Write a Kotlin tail-recursive function to calculate the nth Fibonacci number.

Sample Solution:

Kotlin Code:

tailrec fun fibonacci(n: Int, a: Long = 0, b: Long = 1): Long {
    if (n == 0) {
        return a
    }
    
    return fibonacci(n - 1, b, a + b)
}

fun main() {
    val n = 9
    val fibonacciNumber = fibonacci(n)
    println("The $n-th Fibonacci number is: $fibonacciNumber")
}

Sample Output:

The 9-th Fibonacci number is: 34

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.
  • In the base case, if n becomes 0, it means we have reached the desired position and return the current Fibonacci number a.
  • 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.
  • We use tail recursion by making the recursive call directly without additional computation.
  • The recursive calls continue until the base case is reached and the final Fibonacci number is computed.

Kotlin Editor:


Previous: Sum of numbers from 1 to n.
Next: Calculate the power of a number.

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.