
Sponsored
Sponsored
This approach uses an iterative method to generate Fibonacci numbers. The idea is to maintain two variables representing the last two numbers in the sequence and update them in each iteration.
Time Complexity: O(1) per yield.
Space Complexity: O(1).
1def fib_generator():
2 a, b =
This code defines a generator function fib_generator() which yields Fibonacci numbers indefinitely. It initializes two variables a and b to 0 and 1 (first two Fibonacci numbers) and then enters an infinite loop where it yields a and updates a, b to the next two numbers in the sequence.
This approach uses recursion to generate Fibonacci numbers. This approach is more intuitive but is less common due to the overhead of recursive calls.
Time Complexity: O(1) per call.
Space Complexity: O(1).
1#include <iostream>
2#include <functional>
3#include <iterator>
4
5class Fibonacci {
6 public:
7 Fibonacci() : a(0), b(1) {}
8
9 int next() {
10 int current = a;
11 a = b;
12 b = current + b;
13 return current;
14 }
15
16 private:
17 int a, b;
18};
19
20int main() {
21 Fibonacci fib;
22 for (int i = 0; i < 5; ++i) {
23 std::cout << fib.next() << " "; // Outputs 0 1 1 2 3
24 }
25 return 0;
26}This C++ solution emulates generator behavior using a class called Fibonacci. The class maintains state between calls using private member variables a and b, similar to static variables in a recursive function. The function next() returns the next Fibonacci number.