Write an iterator that yields all Fibonacci numbers up to a given upper bound top. Use it to:
get the highest Fibonacci number less than 1000 (expected 987), and
find whether there is a Fibonacci number ≤ 1000 that is a multiple of 12 (expected 144).
The iterator version mirrors the behaviour of a generator; both yield the same sequence. Generators are usually more concise in Python, but iterators demonstrate how the protocol works under the hood.
classFibonacciIteratorimplements java.util.Iterator<Long> {
privatefinallong top;
privatelong a = 0, b = 1;
FibonacciIterator(long top) { this.top= top; }
publicbooleanhasNext() { return a <= top; }
public Long next() { long r = a; long nxt = a + b; a = b; b = nxt; return r; }
}
1
2
3
4
5
6
7
8
9
10
11
classFibonacciIterator(privateval top: Long) : Iterator<Long> {
privatevar a = 0Lprivatevar b = 1LoverridefunhasNext() = a <= top
overridefunnext(): Long {
val r = a
val nxt = a + b
a = b; b = nxt
return r
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classFibonacciIterator:
def__init__(self, top: int):
self.top = top
def__iter__(self):
self.a =0 self.b =1return self
def__next__(self) -> int:
if self.a > self.top:
raiseStopIteration result = self.a
self.a, self.b = self.b, self.a + self.b
return result
Generators produce the same sequence with less boilerplate. In Python use yield. In Go use a goroutine + channel. The generator approach is concise and clear.
Use generators for concise code in languages that support them (Python, Kotlin, TypeScript). Use iterator classes when you need explicit control over state or to interoperate with APIs expecting an iterator object.
Fibonacci numbers grow exponentially; the k-th Fibonacci is ≈ phi^k / sqrt(5). The number of Fibonacci numbers ≤ top is O(log top).