Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
pp:tailend [2016/05/05 17:43]
vrares [Fibonacci sequence]
pp:tailend [2016/05/05 18:46] (current)
vrares [Fibonacci sequence]
Line 5: Line 5:
 ===== Fibonacci sequence ===== ===== Fibonacci sequence =====
  
-Let us consider the following ​code:+Let us consider the following ​recursive function that computes the n-th Fibonacci number: 
 <​code>​ <​code>​
 int fibo (int n) { int fibo (int n) {
Line 11: Line 12:
     return n;     return n;
   }   }
-  return ​f(n-1) + f(n-2);+  return ​fibo(n-1) + fibo(n-2);
 } }
 </​code>​ </​code>​
 +
 +The code works well and behaves as expected, but let us discuss the above function in terms of efficiency. The function calls are shown below:
 +
 +<​code>​
 +fibo(4) ​                //​ninth evaluation, fibo(4) = fibo(3) + fibo(2) = 2 + 1 = 3
 +|
 ++->​fibo(3) ​             //fifth evaluation, fibo(3) = fibo(2) + fibo(1) = 1 + 1 = 2
 +|  |
 +|  +->​fibo(2) ​          //​third evaluation, fibo(2) = fibo(1) + fibo(0) = 1 + 0 = 1
 +|  |  |
 +|  |  +->​fibo(1) ​       //first evaluation, fibo(1) = 1
 +|  |  |
 +|  |  +->​fibo(0) ​       //second evaluation, fibo(0) = 0
 +|  |
 +|  +->​fibo(1) ​          //​fourth evaluation, fibo(1) = 1
 +|
 ++->​fibo(2) ​             //eighth evaluation, fibo(2) = fibo(1) + fibo(0) = 1 + 0 = 1
 +   |
 +   ​+->​fibo(1) ​          //​sixth evaluation, fibo(1) = 1
 +   |
 +   ​+->​fibo(0) ​          //​seventh evaluation, fibo(0) = 0
 +</​code>​
 +
 +<stack diagram to be inserted here>
 +<work in progress>​