VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-print-first-n-fibonacci-numbers/

⇱ Find First n Fibonacci Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find First n Fibonacci Numbers

Last Updated : 3 Jan, 2025

Given an integer n. The task is to find the first n Fibonacci Numbers.

👁 fibonacci-sequence

Examples :

Input: n = 3
Output: 0 1 1

Input: n = 7
Output: 0 1 1 2 3 5 8

Recursive Approach - O(n*2n) Time and O(n) Space

Find nth fibonacci number by calling for n-1 and n-2 and adding their return value. The base case will be if n=0 or n=1 then the fibonacci number will be 0 and 1 respectively.


Output
0 1 1 2 3 5 8 

Time Complexity: O(n*2n)
Auxiliary Space: O(n), For recursion call stack.

Iterative Approach - O(n) Time and O(1) Space

To find Fibonacci numbers by maintaining two variables (f1 and f2) to represent consecutive Fibonacci numbers. Starting with 0 and 1, it iteratively computes the next Fibonacci number, appends it to the result list, and updates the variables accordingly.


Output
0 1 1 2 3 5 8 

Time Complexity: O(n) 
Auxiliary Space: O(1)


Comment