How does remembering a recursive factor function make it more efficient?

var lookup = {}; function memoized(n) { if(n <= 1) { return 1; } if(lookup[n]) { return lookup[n]; } lookup[n] = n * memoized(n - 1); return lookup[n]; } 

vs.

 function fact(n) { if(n <= 1) { return 1; } return n * fact(n-1); } 

If we call fact (3)

In the second method, we get → 3 * (2 * (1))

What is the effect of efficiently storing the result in a hash. Is it only for subsequent calls to the same function? I cannot understand how you will get anything if you only call the function once.

With a memoized Fibonacci function, even if there is only one function call, there is still an efficiency gain. To get the nth fibonacci number, if you do not memoize, you will repeat the calculation for fib (n-1) and fib (n-2) for each fib (n). I do not see this in a factorial function.

+4
source share
2 answers

in fact, there is no efficiency obtained by using it once. you get efficiency only if this method is used several times

+6
source

Since you save the result of previously calculated factorials in lookup .

so let's say if there is another call to the factorial n=5 that has already been calculated, it will simply return lookup[5] , so further recursive calls will not be required to calculate this number factor.

And, therefore, it will be effective if it serves a lot of requests.

+5
source

Source: https://habr.com/ru/post/1493888/


All Articles