Funny Febo !

Assume a recursive function to find the n th n^\text{th} Fibonacci term. What is the number of calls for that function to find the 7 th 7^\text{th} term?

Details and Assumptions:

  • f ( 0 ) = 1 f(0)=1 , f ( 1 ) = 1 f(1)=1 and f ( 7 ) = 21 f(7)=21
  • f ( z ) = f ( z 1 ) + f ( z 2 ) f(z)=f(z-1)+f(z-2) where z 2 z\ge2

This problem is a part of the set: Efficient Algorithms .


The answer is 41.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

Zeeshan Ali
Jan 22, 2016

1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 1,1,2,3,5,8,13,21\dots The sequence given above is the Fibonacci sequence which can be generalize as:

F 0 = 1 F_0=1 , F 1 = 1 F_1=1 and F n = F n 1 + F n 2 F_n=F_{n-1}+F_{n-2} where n 2 n \ge 2 .

1
2
3
4
5
6
7
8
int F(int n){
    if (n==0 || n==1){
        return 1;
    }
    else{
        return F(n-1)+F(n-2);
    }
}

For exapmle: When we want to find F 2 F_{2} we call the recursive function F 2 F_{2} which then calls F 0 F_{0} and F 1 F_{1} . Hence we say the function is called thrice.

Here is a list which gives the Fibonacci sequence in the first column and the number of function calls to get it:

  • 0 \rightarrow 1

  • 1 \rightarrow 1

  • 2 \rightarrow 3

  • 3 \rightarrow 5

  • 4 \rightarrow 9

  • 5 \rightarrow 15

  • 6 \rightarrow 25

  • 7 \rightarrow 41 \boxed{41}

.

.

.

Since we know that to find n t h n^{th} term we have to find ( n 1 ) t h (n-1)^{th} and ( n 2 ) t h (n-2)^{th} terms. Hence the first call of function is F(n) then the remaining calls for F(n-1) and F(n-2). Therefore N(F(n))=1+N(F(n-1))+N(F(n-2)).

The image below is a tree that shows the total number of function calls to find 6 t h 6^{th} term:

  • The r e c u r s i v e f u n c t i o n recursive \, function in C++ that can do the task of finding the t o t a l n u m b e r o f f u n c t i o n c a l l s total \, number \, of \, function \, calls is:
1
2
3
4
5
6
7
8
int Nf(int n){
    if (n==0 || n==1){
        return 1;
    }
    else{
        return Nf(n-1)+Nf(n-2)+1;
    }
}

I hope that might help you understand the logic behind that function more clearly.

Vijay Kumar
Jan 24, 2016

Here is my implementatio :

cnt = 0
def fibo(n) :
         global cnt
         cnt += 1
         if n < 2 : return 1
         else :
              return fibo(n-1)+fibo(n-2) 

 print cnt

Right.. good work :)

Zeeshan Ali - 5 years, 4 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...