Kotlin – Find Nth Number in the Fibonacci Series

Find Nth Number in Fibonacci Series in Kotlin

In this tutorial, you’ll learn how to find the Nth number in the Fibonacci series using Kotlin, given the value N.

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. It starts with 0 and 1.

0 1 1 2 3 5 8 13 21 34 55 89 ...

The first number is 0, the second number is 1, the third number is 1, the fourth number is 2, the fifth number is 3, and so on.

Example

Finding Nth Fibonacci Number

We’ll start with an example of finding the Nth Fibonacci number.

In this example, the findFibonacci() function calculates the Nth Fibonacci number using recursion. The base cases are when n is 0 or 1, in which case the function returns n. For other values of n, the function calls itself recursively to find the sum of the two preceding Fibonacci numbers.

Kotlin Program

// Function to find Nth Fibonacci number
fun findFibonacci(n: Int): Int {
    if (n <= 1) {
        return n
    } else {
        return findFibonacci(n - 1) + findFibonacci(n - 2)
    }
}

fun main() {
    val n = 6
    val nthFibonacci = findFibonacci(n)
    println("The $n-th Fibonacci number is: $nthFibonacci")
}

Output

The 6-th Fibonacci number is: 8

Summary

In this Kotlin Tutorial, we learned how to find the nth item in the Fibonacci series in Kotlin, with the help of example programs.