
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).
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.