
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).
1function* fibGenerator() {
2 let a
This JavaScript generator function fibGenerator() creates an infinite series of Fibonacci numbers. It maintains two variables a and b for the last two numbers, yielding the current number and computing the next two in each iteration using destructuring assignment.
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.