This one neatly solves problem of log n multiplications to calculate nth power of of some number. It goes in two stages, calls self recursively with half power until it reaches power 0 or 1 and then squares results. If power was not even correction is required, additional multiplication with base.
If we want to see how it works and how many times it calls self we can insert debug code:
Should have been included it in previous blog entries about recursion but better late than never.
No comments:
Post a Comment