Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Program for Fibonacci Numbers
kkumar-gcc
kkumar-gcc

Posted on • Edited on • Originally published atMedium

     

Program for Fibonacci Numbers

What is the Fibonacci series?

The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21 ....
Enter fullscreen modeExit fullscreen mode

In mathematical terms,the sequence Fn of Fibonacci numbers is defined by recursion relation

Fn = Fn-1 + Fn-2
Enter fullscreen modeExit fullscreen mode

where

F0 = 0 , F1 = 1
Enter fullscreen modeExit fullscreen mode

We will discuss three ways to write the Fibonacci series program :

  • Fibonacci series using recursion
  • Fibonacci series using Iterative method
  • Fibonacci series using Matrix Exponentiation

(1) Recursive Method :

A simple method that is a direct recursive implementation mathematical recurrence relation is given above.

//pseudo code RFib(n){  if n=0 return 0;    else if n=1 return 1;         else return (RFib(n-1)+RFib(n-2));}
Enter fullscreen modeExit fullscreen mode

Time Complexity: T(n) = T(n-1) + T(n-2) which is exponential.
Extra Space: O(n) if we consider the function call stack size, otherwise O(1).

Run Replit

(2) Iterative Method :

We can optimize the space used in Recursive Method by storing the previous two numbers only because that is all we need to get the next Fibonacci number in series.

//pseudo code IFib(n)if n=0 return 0;   else if n=1 return 1;        else {   a <= 0; b<=1;            for(i=2 to n) do            { temp <= b;              b<= a+b;              a <= temp;            }return b;
Enter fullscreen modeExit fullscreen mode

Time complexity: O(n) 
Extra space: O(1)

Run Replit

(3) Matrix Exponentiation :

Let n > 1

Matrix Exponentiation

pseudo code

Time complexity : O(log(n))
Extra space : O(log(n)) if we consider the function call stack size, otherwise O(1).

Run Replit

Thanks for reading

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp