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.
Using Kotlin:
Generate a
Sequence
(infinite stream of data) starting with 1, 1. Each next element is the second number of the pair + their sum. UseelementAt
to get the n-th pair. The result is the first number of the pair.Try it out online: pl.kotl.in/MOeDSCD4v