DEV Community

Discussion on: Let's Get Clever #1: Fibonacci Sequence

Collapse
 
s_anastasov profile image
Stojan Anastasov

Using Kotlin:

fun fib(n: Int): Int = generateSequence(Pair(1, 1)) {
    Pair(it.second, it.first + it.second)
}.elementAt(n).first

Generate a Sequence (infinite stream of data) starting with 1, 1. Each next element is the second number of the pair + their sum. Use elementAt to get the n-th pair. The result is the first number of the pair.

Try it out online: pl.kotl.in/MOeDSCD4v