This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Recursion

Will Myers
Ranch Hand
Posts: 378
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
Posts: 12086
29
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)

Ulf Dittmer
Rancher
Posts: 42967
73