public
Authored by avatar CattenLinger :sparkles:

[Kotlin] Fibonacci Iterator

An iterator implementation that produces numbers from the Fibonacci sequence.

FibonacciIterator.kt 583 bytes
import java.math.BigDecimal

class FibonacciIterator : Iterator<BigDecimal> {
    var generations = 0L
        private set

    private var ancient = BigDecimal(0)
    private var parents = BigDecimal(1)

    override fun hasNext(): Boolean {
        return generations < Long.MAX_VALUE
    }

    override fun next(): BigDecimal {
        return when(generations) {
            0L -> ancient
            1L -> parents
            else -> (ancient + parents).also {
                ancient = parents
                parents = it
            }
        }.also { generations++ }
    }
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment