473,383 Members | 1,737 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

New to recursion

40
Hi
I just started reading about recursion so I'm not sure how things work. I can find general information about recursion but not as analytical as I would like it to be.

Say I have this code that computes Fibonacci numbers...

Expand|Select|Wrap|Line Numbers
  1. public static long fib(int n){
  2.  
  3. if (n <= 1)
  4.     return 1;
  5. else
  6.    return fib(n-1) + fib(n-2);
  7. }
  8.  
Say now that n = 5.
What exactly happens when line 6 is read? The method should return fib(4) + fib(3). Does it first compute fib(4) and only when it has a result computes fib(3)?
I understand than in order to compute fib(4) or fib(3) it has first to compute fib(2) and fib(1) which is the base case but I'm confused about the order in which this works.

Thanks a lot,
stack
Feb 16 '08 #1
7 1296
Ganon11
3,652 Expert 2GB
I believe that the first call to fib in the return statement is evaluated first. The call to fib, then, looks like this:

Expand|Select|Wrap|Line Numbers
  1. n = 5
  2. fib(5);
  3.   5 > 1, so
  4.   fib(4);
  5.     4 > 1, so
  6.     fib(3);
  7.       3 > 1, so
  8.       fib(2);
  9.         2 > 1, so
  10.         fib(1);
  11.           1 <= 1, so return 1;
  12.         fib(0);
  13.           0 <= 1, so return 0;
  14.         return 1+0;
  15.  
  16.       fib(1);
  17.         1 <= 1, so return 1;
  18.     return 1+1;
  19.  
  20.     fib(2);
  21.       2 > 1, so
  22.         fib(1);
  23.           1 <= 1, so return 1;
  24.         fib(0);
  25.           0 <= 1, so return 0;
  26.       return 1+0;
  27.   return 2+1;
  28.  
  29.   fib(3);
  30.     3 > 1, so
  31.     fib(2);
  32.       2 > 1, so
  33.         fib(1);
  34.           1 <= 1, so return 1;
  35.         fib(0);
  36.           0 <= 1, so return 0;
  37.       return 1+0;
  38.     fib(1);
  39.       1 <= 1, so return 1;
  40.     return 1+1;
  41.   return 3+2;
  42.  
See how many function calls are made for a very small initial value? That's why using recursion to find Fibonacci numbers is a TERRIBLE idea. But that's how the recursion works.
Feb 16 '08 #2
BigDaddyLH
1,216 Expert 1GB
See how many function calls are made for a very small initial value? That's why using recursion to find Fibonacci numbers is a TERRIBLE idea. But that's how the recursion works.
Of course, don't generalize from this that recursion is *bad*. There are many problems, like sorting data, where the optimal solution can be done with recursion. And there are many problems where recursion is the clearest, simplest, most logical and most elegant solution.
Feb 16 '08 #3
BigDaddyLH
1,216 Expert 1GB
Hi
I just started reading about recursion so I'm not sure how things work. I can find general information about recursion but not as analytical as I would like it to be.

Say I have this code that computes Fibonacci numbers...

Expand|Select|Wrap|Line Numbers
  1. public static long fib(int n){
  2.  
  3. if (n <= 1)
  4.     return 1;
  5. else
  6.    return fib(n-1) + fib(n-2);
  7. }
  8.  
Say now that n = 5.
What exactly happens when line 6 is read? The method should return fib(4) + fib(3). Does it first compute fib(4) and only when it has a result computes fib(3)?
I understand than in order to compute fib(4) or fib(3) it has first to compute fib(2) and fib(1) which is the base case but I'm confused about the order in which this works.

Thanks a lot,
stack
Realize that these questions have little or nothing to do with recursion. What if the code had been:
Expand|Select|Wrap|Line Numbers
  1. public static long fib(int n){
  2. if (n <= 1)
  3.     return 1;
  4. else
  5.    return gib(n-1) + hib(n-2);
  6. }
  7.  
The questions you raise are just as valid for this function. So why didn't you ask them before you got to studying recursion? I think people are subtlely taught that recursion is hard, when I honesty believe it's easier than a lot of other things to understand, for example, loops.
Feb 16 '08 #4
Ganon11
3,652 Expert 2GB
Of course, don't generalize from this that recursion is *bad*. There are many problems, like sorting data, where the optimal solution can be done with recursion. And there are many problems where recursion is the clearest, simplest, most logical and most elegant solution.
Exactly. Another great example of recursion can be found in many of the popular solutions to tree problems, such as searching, inserting, etc. Even though these can be solved with loops, recursion is a very intuitive solution.
Feb 16 '08 #5
stack
40

Expand|Select|Wrap|Line Numbers
  1. n = 5
  2. fib(5);
  3.   5 > 1, so
  4.   fib(4);
  5.     4 > 1, so
  6.     fib(3);
  7.       3 > 1, so
  8.       fib(2);
  9.         2 > 1, so
  10.         fib(1);
  11.           1 <= 1, so return 1;
  12.         fib(0);
  13.           0 <= 1, so return 0;
  14.         return 1+0;
  15. .....
  16.  
  17.  
This is the kind of answer I was hoping for. Thank you very much.

One more thing. The "return 0" should be "return 1", right?

Reagards,
stack
Feb 17 '08 #6
Ganon11
3,652 Expert 2GB
Ah, yes - in your example. Some recursive fib. sequence functions return 0 if n is 0, or 1 if n is 1. It doesn't affect the series very much, just puts a 0 in front, and this is how I assumed it would be written. So...all the returns are wrong, but do you get the idea of how a simple call to fib() is evaluated?
Feb 17 '08 #7
stack
40
Ah, yes - in your example. Some recursive fib. sequence functions return 0 if n is 0, or 1 if n is 1. It doesn't affect the series very much, just puts a 0 in front, and this is how I assumed it would be written. So...all the returns are wrong, but do you get the idea of how a simple call to fib() is evaluated?
I draw a tree for all fib calls where every node has 2 children (n-1) and (n-2) and now everything makes sense :-)

Thanks again!
stack
Feb 17 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Peri | last post by:
I'm trying to create Python parser/interpreter using ANTLR. Reading grammar from language refference I found: or_expr::= xor_expr | or_expr "|" xor_expr For me it looks like infinite recursion....
12
by: da Vinci | last post by:
Greetings. I want to get everyone's opinion on the use of recursion. We covered it in class tonight and I want a good solid answer from people in the "know" on how well recursion is accepted...
43
by: Lorenzo Villari | last post by:
I've tried to transform this into a not recursive version but without luck... #include <stdio.h> void countdown(int p) { int x;
2
by: Csaba Gabor | last post by:
I suppose spring fever has hit at alt.math.undergrad since I didn't get any rise from them when I posted this a week ago, so I am reposting this to some of my favorite programming groups: I'm...
75
by: Sathyaish | last post by:
Can every problem that has an iterative solution also be expressed in terms of a recursive solution? I tried one example, and am in the process of trying out more examples, increasing their...
19
by: Kay Schluehr | last post by:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
18
by: MTD | last post by:
Hello all, I've been messing about for fun creating a trial division factorizing function and I'm naturally interested in optimising it as much as possible. I've been told that iteration in...
13
by: robert | last post by:
My code does recursion loops through a couple of functions. Due to problematic I/O input this leads sometimes to "endless" recursions and after expensive I/O to the Python recursion exception. What...
20
by: athar.mirchi | last post by:
..plz define it.
35
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.