How does memoizing a recursive factorial function make it more efficient?

老子叫甜甜 提交于 2019-12-22 08:37:42

问题


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)

With the second method we get --> 3 * (2 * (1))

What is the efficiency gain of storing the result in a hash. Is it only for subsequent calls to the same function? I can't see how you would gain anything if you are only calling the function once.

With the 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 be repeating the calculation for fib(n-1) and fib(n-2) on each fib(n). I don't see this happening in the factorial function.


回答1:


actually there is no efficiency gained by using it once. you gain efficiency only if this method is used several times




回答2:


Because you are storing the result of previously calculated factorials in lookup.

so let's say if there is another call for factorial of n=5 which already calculated it'll just return lookup[5] so no further recursive calls will be required for calculating that number's factorial.

And hence it'll more efficient if it is going to serve many requests.



来源:https://stackoverflow.com/questions/17905766/how-does-memoizing-a-recursive-factorial-function-make-it-more-efficient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!