Created
May 30, 2021 15:43
-
-
Save CattenLinger/93d3142676935325b343984d23943c12 to your computer and use it in GitHub Desktop.
An iterator implementation that produces numbers from the Fibonacci sequence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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++ } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment