Print Fibonacci Series

Easy
0/40
Average time to solve is 10m
profile
Contributed by
115 upvotes
Asked in companies
ToXSL Technologies Pvt LtdNewgen SoftwareConsuma

Problem statement

Given an integer ‘n’, return first n Fibonacci numbers using a generator function.


Example:
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.
Detailed explanation ( Input/output format, Notes, Images )
Input Format
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.
Sample Input 1:
5
Sample Output 1:
0 1 1 2 3
Explanation Of Sample Input 1:
The first 5 Fibonacci numbers are 0, 1, 1, 2, and 3.
Sample Input 2:
3
Sample Output 2:
0 1 1
Explanation Of Sample Input 2:
The first 5 Fibonacci numbers are 0, 1, 1.
Expected time complexity
The expected time complexity is O(n).
Constraints:
1 <= n <= 45
Time Limit: 1 s
Hint

Use a while loop inside the generator function to get the Fibonacci numbers.

Approaches (2)
Intuitive Approach

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

  1. Initialize a variable ‘count’, which is initially assigned to 1.
  2. Initialize two more variables, ‘a’ and ‘b’, each assigned to 0 and 1, respectively.
  3. While count <= n:
    • yield a.
    • Assign ‘b’ to ‘a’ and ‘a + b’ to ‘b’.
    • Increment count.

 

// Function to generate first n Fibonacci numbers

function generateFibonacciNumbers(int n):

  1. Create an empty list, ‘listOfIntegers’, which stores the Fibonacci Numbers.
  2. Iterate over each item produced by generatorFunction(n):
    • Insert the value in the list ‘listOfIntegers’.
  3. Return ‘listOfIntegers’.
Time Complexity

O( n ), where n is the given number.

 

We iterate for n times using the while loop,

 

Hence the time complexity is O( n ).

Space Complexity

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

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Print Fibonacci Series
Full screen
Console