Given an integer ‘n’, return first n Fibonacci numbers using a generator function.
Input: ‘n’ = 5
Output: 0 1 1 2 3
Explanation: First 5 Fibonacci numbers are: 0, 1, 1, 2, and 3.
Note:
You don't need to print anything. Just implement the given function.
The first and only input line contains one integer, n, the required number of Fibonacci numbers to return.
Output format:
Return first n Fibonacci numbers using a generator function.
5
0 1 1 2 3
The first 5 Fibonacci numbers are 0, 1, 1, 2, and 3.
3
0 1 1
The first 5 Fibonacci numbers are 0, 1, 1.
The expected time complexity is O(n).
1 <= n <= 45
Time Limit: 1 s
Use a while loop inside the generator function to get the Fibonacci numbers.
Create a generator function ‘generatorFunction’, which takes the number of Fibonacci numbers to return (say this is ‘n’). In this function, create a variable ‘count’ initially assigned to one. Create two more variables, ‘a’ and ‘b’, each assigned to 0 and 1, respectively. Now, use a while loop on ‘count’ variable from ‘1’ to’ ‘n’. In each iteration, first, yield ‘a’ and then assign ‘b’ to ‘a’ and ‘a + b’ to ‘b’.
Now, create an empty list, iterate over the ‘generator’ object and insert the items in the list. And Finally, return the list.
The steps are as follows:-
// Generator function to generate Fibonacci numbers
function generatorFunction(int n):
// Function to generate first n Fibonacci numbers
function generateFibonacciNumbers(int n):
O( n ), where n is the given number.
We iterate for n times using the while loop,
Hence the time complexity is O( n ).
O( n ), where n is the given number.
We store the series in a list, and it will store N elements,
Hence the space complexity is O( n ).