Question

say there is a function to calculate factorial(n)

Does factorial(7) creates 7 function object for each of n from 1 to 7

and use those values when ever necessary (for factorial(8) as like factorial(7)*8)

Was it helpful?

Solution

It depends on the language and the language implementation.

In many functional languages (e.g. Haskell), a function is guaranteed to change nothing; only to return a value. This lack of side effects allows the language to remember/cache, or "memoize", the results of function calls.

In a less sophisticated language, 7 distinct function call frames might be placed on the stack and popped off.

A properly written factorial function in many functional languages would also be tail recursive; in that case the language might choose to simply jump from the bottom of the function to the top to avoid creating another function call. In this case the language is turning the recursive function into a loop "for free".

OTHER TIPS

It depends, sounds like you are talking about a recursive factorial function:

int factorial(int n) {
    return n>=1 ? n * factorial(n-1) : 1;
}

This function will invoke itself recursively the number of times needed to calculate the given factorial(n).

Mostly all recursive functions can be transformed into an iterative solution by using a stack to accumulate the consecutive results...

int factorial(int n) {
    int accu = 1;
    int i;
    for(i = 1; i <= n; i++) {
        accu *= i;
    }
    return accu;
}

It can. What you're asking sounds like memoization -- you store previous results to speed computations later. So, for example, if you compute 9!, you can store the values for 1! .. 9!, and if you're asked for 8! later you can just return the stored value. Similarly, if asked for 10!, you can compute 10×9! quickly.

The thing is that factorial(n) grows so quickly, for large values of n you can end up using a lot of storage, so the space-time trade may not be worthwhile.

Another function that can use memoization effectively is computing Fibonacci numbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top