In this post, I will show how to find Fibonacci number by index in Kotlin

Fibonacci numbers are sequence numbers which start with 0 and 1, next numbers are a sum of previous two numbers.

For example: 0, 1, 1, 2, 3, 5, 8, 13 and so on. In this example 8 is a sum of 3 and 5.

This code is Kotlin and it finds Fibonacci number by its index

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
fun main(args: Array<String>) { println(fibonacci(6)) } fun fibonacci(index: Int): Int{ if(index<2) return index; var a = 0; var b = 1; for (i in 2..index){ var c = a+b; a = b; b = c; } return b; } |