




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).
1using System;
2using System.Collections.Generic;
3
4public class Fibonacci
5{
6    public static IEnumerable<int> Generate()
7    {
8        int a = 0, b = 1;
9        while (true)
10        {
11            yield return a;
12            int temp = a;
13            a = b;
14            b = temp + b;
15        }
16    }
17
18    public static void Main()
19    {
20        var fibonacci = Generate();
21        using var enumerator = fibonacci.GetEnumerator();
22        for (int i = 0; i < 5; i++)
23        {
24            enumerator.MoveNext();
25            Console.WriteLine(enumerator.Current); // Outputs 0, 1, 1, 2, 3
26        }
27    }
28}This C# solution uses an IEnumerable to yield Fibonacci numbers indefinitely. The sequence is handled within the Generate() method using yield return. A loop iteratively provides access to each Fibonacci number.