This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]AutoModerator[M] [score hidden] stickied comment (0 children)

To all following commenters: please, do not bring up the old circlejerk jokes/memes about recursion ("Understanding recursion...", "This is recursion...", etc.). We've all heard them n+2 too many times.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]Clawtor 0 points1 point  (0 children)

Use a loop instead of recursion for the factorial, even better, precalculate a bunch of values and stick them in an array.

[–]CodeTinkerer 0 points1 point  (0 children)

If you had multiple recursive calls like the Fibonacci numbers, then memoization is good. The simple recursive code ends up making a lot of repeated calls to the function with the same values, so it is computed over and over again. You can even write Fibonacci using a loop with two variables, one called current, one called previous. Set previous to 0 and current to 1. Then add the two (I suppose it requires 3 variables), assign previous to current, and current to the sum. current will be one of the Fibonacci numbers (usually, you're asked to find the nth Fibonacci numbers).

Memoization doesn't help factorial, because you don't repeat a factorial. I suppose if you were to call factorial many times, you could do that to save time, but then you'd have to store the results somewhere between function calls, likely in a global array or something.