Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Recursion  RSS feed

 
Ranch Hand
Posts: 440
Java jQuery Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
lowercase baba
Posts: 12628
50
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Rancher
Posts: 42974
76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Either that, or just follow the link.
 
Will Myers
Ranch Hand
Posts: 440
Java jQuery Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Fred!

Nice work Ulf
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!