Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Print Fibonacci Series

Easy
0/40
Average time to solve is 10m
profile
Contributed by
103 upvotes

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
All tags
Sort by
Search icon

Interview problems

have you seen that

using a simple fibonacci function we implement using a array and printing an array;

 

JAVA – 

 

public static int[] generateFibonacciNumbers(int n) {
        // Write your code here.
        int[] arr = new int[n];
        if (n == 1){
            arr[0] = 0;
            return arr;
        }
        arr[0] = 0;
        arr[1] = 1;
        for (int i = 2;i<n;i++){
            arr[i] = arr[i-1] + arr[i-2];
        }
        return arr;

    }
13 views
1 reply
1 upvote

Interview problems

C++ easiest solution

vector<int> generateFibonacciNumbers(int n) {

    // Write your code here.

    if(n==1){

        vector<int> res;

        int num1 = 0;

        res.push_back(num1);

        return res;

    }

    else if(n==2){

        vector<int> res;

        int num1 = 0;

        int num2 = 1;

        res.push_back(num1);

        res.push_back(num2);

        return res;

    }

    vector<int> res;

    int num1 = 0;

    int num2 = 1;

    res.push_back(0);

    res.push_back(1);

    int num3;

    for(int i = 0; i<n-2; i++){

        num3 = num1 + num2;

        res.push_back(num3);

        num1=num2;

        num2=num3;

    }

    return res;

}

24 views
0 replies
0 upvotes

Interview problems

Java

public class Solution {
    public static void fillArray(int count, int N, int[] result) {
        if (count >= N) {
            return; 
        }
        if (count <= 1 ) {
            result[count] = count;
        } else {
            result[count] = result[count - 1] + result[count - 2]; 
        }
        fillArray(count + 1, N, result);
    }

    public static int[] generateFibonacciNumbers(int n) {
        // Create an array to hold Fibonacci numbers
        int[] result = new int[n];
        fillArray(0, n, result); 
        return result; 
    }
}

java

programming

31 views
0 replies
0 upvotes

Interview problems

easy cpp solution

vector<int> generateFibonacciNumbers(int n) {

    vector<int> temp(n);

    temp[0]=0;

    temp[1]=1;

    for(int i = 2; i<n; i++) {

        temp[i] = temp[i-1] + temp[i-2];

    }

    return temp;

}

93 views
0 replies
1 upvote

Interview problems

simpler code||c++

vector<int> generateFibonacciNumbers(int n) {

  // Write your code here.

  vector<int> arr(n);

  arr[0] = 0;

  arr[1] = 1;

 

  for (int i = 2; i < n; i++) {

    arr[i] = arr[i - 1] + arr[i - 2];

  }

  return arr;

}

127 views
0 replies
0 upvotes

Interview problems

Print Fibonacci Series

You have to declare the vector and push all the next element in vector, before it we compare the element if (n <= 0) {

        return fibonacci; // Return an empty vector if n is less than or equal to 0

    }

    

    fibonacci.push_back(0);

    if (n == 1) {

        return fibonacci; // Return a vector with only the first element if n is 1

    }

 

    fibonacci.push_back(1);

    int first = 0;

    int second = 1;

 

after that we use the for loop 

 

 

112 views
0 replies
0 upvotes

Interview problems

The python code it is the smallest you can find here please upvote👇

from typing import List

 

def generateFibonacciNumbers(n: int) -> List[int]: 

     fib = [0, 1]

 

     while len(fib) < n:

        fib.append(fib[-1] + fib[-2])

 

     return fib[:n]

 

53 views
0 replies
1 upvote

Interview problems

i want fortran 1V compiling

FORTRAN IV

5 views
0 replies
0 upvotes

Interview problems

Print Fibonacci Series in C++

vector<int> generateFibonacciNumbers(int n) {

    // Write your code here.

    vector<int>fib;

    if(n==0) 

    return fib;

    fib.push_back(0);

    if(n==1)

    return fib;

    fib.push_back(1);

    for(int i=2;i<n;i++){

        int nextnum=fib[i-1]+fib[i-2];

        fib.push_back(nextnum);

    }

   return fib;

}

178 views
0 replies
2 upvotes

Interview problems

Print Fibonacci Series || Java

public class Solution {
    public static int[] generateFibonacciNumbers(int n) {
        int arr[] = new int[n];
        for (int i=0; i<n; i++) {
            if (i==0 || i==1) {
                arr[i] = i;
            } else {
                arr[i] = arr[i-1] + arr[i-2];
            }            
        }
        return arr;
    }
}
165 views
0 replies
1 upvote
Full screen
Console