wood burning stoves 2.0*
The moose likes Java in General and the fly likes Recursion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Recursion" Watch "Recursion" New topic
Author

Recursion

Will Myers
Ranch Hand

Joined: Aug 05, 2009
Posts: 313

I was wondering if anyone had a good simple explanation of how to work out what the result is from a recursive method? For example the following produces 24 as the result when you pass in 4... (1 * 2 * 3 * 4 = 24)



but how would you break it down if presented with this sort of question in an interview?

Another example would be


which will return 28 if you pass in 3 and 4 as the args but again how would you work this out manually? Is there a standard formula for breaking these down?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10923
    
  12

paper and pencil is what I would do. if you pass in 3 and 4, it would return

(3 + 4) * recursion(2,2)

that would return

(3+4) * ( (2+2)* (recursion(1,0) )

that would return

(3 + 4) * ( (2+2) * 1)


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39571
    
  27
Either that, or just follow the link.


Ping & DNS - updated with new look and Ping home screen widget
Will Myers
Ranch Hand

Joined: Aug 05, 2009
Posts: 313

thanks Fred!

Nice work Ulf
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Recursion
 
Similar Threads
recursion situation baffles me
Java endian and bit order and signed and unsigned and python and more confusion than I can deal with
Project Euler #17
SCJP problem with boxing
help in solving recursive problems??