Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does memoizing a recursive factorial 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)

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.

like image 810
ordinary Avatar asked Jul 28 '13 06:07

ordinary


People also ask

Would Memoizing the recursive solution improve the running time?

In the case of the factorial function, an algorithm only benefits from the optimization of memoization when a program makes repeated calls to the function during its execution. In some cases, however, memoization can save time even for a single call to a recursive function.

What does it mean to memoize a function?

In programming, memoization is an optimization technique that makes applications more efficient and hence faster. It does this by storing computation results in cache, and retrieving that same information from the cache the next time it's needed instead of computing it again.

What is the function of factorial with recursive?

The factorial function can be written as a recursive function call. Recall that factorial(n) = n × (n – 1) × (n – 2) × … × 2 × 1. The factorial function can be rewritten recursively as factorial(n) = n × factorial(n – 1).

For which problem it is optimal to use recursion?

Recursion is made for solving problems that can be broken down into smaller, repetitive problems. It is especially good for working on things that have many possible branches and are too complex for an iterative approach .


2 Answers

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

like image 65
No Idea For Name Avatar answered Sep 27 '22 20:09

No Idea For Name


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.

like image 32
VishalDevgire Avatar answered Sep 27 '22 22:09

VishalDevgire