Time complexity of recursive Fibonacci program - GeeksforGeeks (2024)

Skip to content

Time complexity of recursive Fibonacci program - GeeksforGeeks (1)

Last Updated : 22 Feb, 2024

Improve

Improve

Like Article

Like

Save

Report

The Fibonacci numbers are the numbers in the following integer sequence 0, 1, 1, 2, 3, 5, 8, 13… Mathematically Fibonacci numbers can be written by the following recursive formula.

For seed values F(0) = 0 and F(1) = 1
F(n) = F(n-1) + F(n-2)

Before proceeding with this article make sure you are familiar with the recursive approach discussed in Program for Fibonacci numbers.

Analysis of the recursive Fibonacci program:

We know that the recursive equation for Fibonacci is = T(n-1) + T(n-2) + O(1).

What this means is, the time taken to calculate fib(n) is equal to the sum of time taken to calculate fib(n-1) and fib(n-2). This also includes the constant time to perform the previous addition. On solving the above recursive equation we get the upper bound of Fibonacci as O(2n) but this is not the tight upper bound. The fact that Fibonacci can be mathematically represented as a linear recursive function can be used to find the tight upper bound. Now Fibonacci is defined as F(n) = F(n-1) + F(n-2)

  • The characteristic equation for this function will be x2 = x+x2-x-1 = 0.
  • Solving this by quadratic formula we can get the roots as x = (1+√5)/2 and x = (1-√5)/2 .
  • Now we know that solution of a linear recursive function is given as F(n)

F(n) = (α1)n + (α2)n where α1 and α2 are the roots of the characteristic equation. So for our Fibonacci function F(n) = F(n-1) + F(n-2) the solution will be:

F(n) = ( (1+√5)/2 )n + ( (1-√5)/2 )n  

Clearly T(n) and F(n) are asymptotically the same as both functions are representing the same thing. Hence it can be said that:

T(n) = O( ( (1+√5)/2 )n + ( (1-√5)/2 )n ) or we can write below (using the property of Big O notation that we can drop lower order terms).

  • T(n) = O ( (1+√5)/2 )n
  • T(n) = O(1.6180)n , This is the tight upper bound of fibonacci.

Fun Fact: 1.6180 is also called the golden ratio. You can read more about golden ratio here: Golden Ratio in Maths


Time complexity of recursive Fibonacci program - GeeksforGeeks (2)

GeeksforGeeks

Improve

Please Login to comment...

Similar Reads

Time Complexity and Space Complexity

Generally, there is always more than one way to solve a problem in computer science with different algorithms. Therefore, it is highly required to use a method to compare the solutions in order to judge which one is more optimal. The method must be: Independent of the machine and its configuration, on which the algorithm is running on.Shows a direc

14 min read

C program for Time Complexity plot of Bubble, Insertion and Selection Sort using Gnuplot

Prerequisite:Comparison among bubble sort, insertion sort and selection sort. Write a C program to plot and analyze the time complexity of Bubble sort, Insertion sort and Selection sort (using Gnuplot). As per the problem we have to plot a time complexity graph by just using C. So we will be making sorting algorithms as functions and all the algori

5 min read

Check if a M-th fibonacci number divides N-th fibonacci number

Given two numbers M and N, the task is to check if the M-th and N-th Fibonacci numbers perfectly divide each other or not.Examples: Input: M = 3, N = 6 Output: Yes F(3) = 2, F(6) = 8 and F(6) % F(3) = 0 Input: M = 2, N = 9 Output: Yes A naive approach will be to find the N-th and M-th Fibonacci numbers and check if they are perfectly divisible or n

8 min read

Check if sum of Fibonacci elements in an Array is a Fibonacci number or not

Given an array arr[] containing N elements, the task is to check if the sum of Fibonacci elements of the array is a fibonacci number or not.Examples: Input: arr[] = {2, 3, 7, 11} Output: Yes Explanation: As there are two Fibonacci numbers in the array i.e. 2 and 3. So, the sum of Fibonacci numbers is 2 + 3 = 5 and 5 is also a Fibonacci number. Inpu

7 min read

Comparison of an Array and Hash table in terms of Storage structure and Access time complexity

Arrays and Hash Tables are two of the most widely used data structures in computer science, both serving as efficient solutions for storing and accessing data in Java. They have different storage structures and time complexities, making them suitable for different use cases. In this article, we will explore the differences between arrays and hash t

3 min read

Time Complexity Analysis | Tower Of Hanoi (Recursion)

Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk ca

2 min read

Queries of nCr%p in O(1) time complexity

Given Q queries and P where P is a prime number, each query has two numbers N and R and the task is to calculate nCr mod p. Constraints: N <= 106 R <= 106 p is a prime number Examples: Input: Q = 2 p = 1000000007 1st query: N = 15, R = 4 2nd query: N = 20, R = 3 Output: 1st query: 1365 2nd query: 1140 15!/(4!*(15-4)!)%1000000007 = 1365 20!/(2

9 min read

Python Code for time Complexity plot of Heap Sort

Prerequisite : HeapSort Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. We implement Heap Sort here, call it for different sized random lists, meas

3 min read

How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?

Pre-requisite: Sieve of Eratosthenes What is Sieve of Eratosthenes algorithm? In order to analyze it, let's take a number n and the task is to print the prime numbers less than n. Therefore, by definition of Sieve of Eratosthenes, for every prime number, it has to check the multiples of the prime and mark it as composite. This process continues unt

3 min read

Time Complexity of Euclidean Algorithm

In this article, we will discuss the time complexity of the Euclidean Algorithm which is O(log(min(a, b)) and it is achieved. Euclid's Algorithm: It is an efficient method for finding the GCD(Greatest Common Divisor) of two integers. The time complexity of this algorithm is O(log(min(a, b)). Recursively it can be expressed as: gcd(a, b) = gcd(b, a%

4 min read

Time complexity of recursive Fibonacci program - GeeksforGeeks (3)

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

Time complexity of recursive Fibonacci program - GeeksforGeeks (4)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); jQuery('.suggest-bottom-btn').on('click', function(){ var suggest_val = $.trim($("#suggestion-section-textarea").val()); var error_msg = false; if(suggest_val != ""){ if(suggest_val.length <= 2000){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify({ "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

` }), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').html("Sent "); setTimeout(() => { jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); }, 1000); }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('#suggestion-modal-alert').html("Character limit exceeded."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('#suggestion-modal-alert').html("Enter valid input."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } }) $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

Time complexity of recursive Fibonacci program - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 5564

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.