Problem Description
Write a generator function that returns a generator object which yields the Fibonacci sequence. The Fibonacci sequence is defined by the relation Xn = Xn-1 + Xn-2. The first few numbers of the series are 0, 1, 1, 2, 3, 5, 8, 13.
Key Insights
- The Fibonacci sequence starts with 0 and 1.
- Each subsequent number is the sum of the two preceding ones.
- A generator function is suitable for this problem as it allows for on-demand generation of Fibonacci numbers.
- The function should handle cases where the callCount is zero, returning an empty sequence.
Space and Time Complexity
Time Complexity: O(n) - Each Fibonacci number is computed once. Space Complexity: O(1) - Only a constant amount of space is used for storing the last two Fibonacci numbers.
Solution
To solve the problem, we will use a generator function that yields Fibonacci numbers. The function will maintain two variables to hold the last two Fibonacci numbers and will update them iteratively. Each time the generator's next()
method is called, it will yield the next number in the sequence until the specified count is reached.