Connecting Tech Pros Worldwide Help | Site Map

Which one is better and why?

Newbie
 
Join Date: Aug 2009
Posts: 5
#1: 3 Weeks Ago
Is recursive function for calculating Fibonacci series or iterative function is better?
ITERATIVE:
Expand|Select|Wrap|Line Numbers
  1. int fibonacci_iterative(int n)      //Iterative formula for fibonacci series
  2. {
  3.   int f0 = 0;
  4.   int f1 = 1;
  5.   int i, fn;
  6.  
  7.   if (n == 0)
  8.         return 0;
  9.   if (n == 1)
  10.         return 1;
  11.  
  12.   for(i = 2; i <= n; i++)
  13.   {
  14.     fn = f0 + f1;
  15.     f0 = f1;
  16.     f1 = fn;
  17.   }
  18.   return f1;
  19. }
  20.  
RECURSIVE
Expand|Select|Wrap|Line Numbers
  1. int fibonacci_recursive(int nNumber)   //Recursive formula for fibonacci series
  2. {
  3.     if (nNumber == 0)
  4.         return 0;
  5.     if (nNumber == 1)
  6.         return 1;
  7.     return fibonacci_recursive(nNumber-1) + fibonacci_recursive(nNumber-2);
  8. }
  9.  
Expert
 
Join Date: Mar 2008
Location: Naperville, Illinois U.S.
Posts: 828
#2: 3 Weeks Ago

re: Which one is better and why?


The stack usage for the iterative function is invariant -- it is the same regardless of the input argument.

The stack usage for the recursive function is proportional to the input value.

The recursive function is smaller and easier to understand.

I haven't done an analysis, but it looks to me like the recursive function will be slower than the iterative function.

Which is "better"? It is a trade-off between these factors. In some contexts, ease of understanding will trump everything else; in other contexts (most notably embedded systems), stack usage trumps everything else.
Reply

Tags
beginner, c++, function, iterative, recursive