简体   繁体   中英

why is this factorial recursive function inefficient?

In the book "Think like a programmer", the following recursive function is said to be "highly inefficient" and I can't figure out why (the book does not explain). It doesn't seem like there are any unnecessary calculations being done. Is it because of the overhead of calling so many functions (well the same function multiple times) and thus setting up environments for each call to the function?

int factorial(int n) {
  if (n == 1) return 1;
  else return n * factorial(n-1);
}

It is inefficient in two ways, and you hit one of them:

It is recursive, instead of iterative. This will be highly inefficient if tail-call optimization is not enabled. (To learn more about tail-call optimization, look here .) It could have been done like this:

int factorial(int n)
{
    int result = 1;
    while (n > 0)
    {
        result *= n;
        n--;
    }
    return result;
}

or, alternatively, with a for loop.

However, as noted in comments above, it doesn't really matter how efficient it is if an int can't even hold the result. It really should be long s, long long s, or even big-ints.

The second inefficiency is simply not having an efficient algorithm. This list of factorial algorithms shows some more efficient ways of computing the factorial by decreasing the number of numerical operations.

There is significant function call overhead in C when not using a compiler that implements tail call optimization.

Function call overhead is the extra time and memory necessary for a computer to properly set up a function call.

Tail call optimization is a method of turning recursive functions like the one given into a loop.

I think the book writer may want to tell readers to not abuse recursion. For this function you could just use:

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

Recursion is slower as well as memory eater in terms of Memory Stack.It is a time taking work to push info onto the stack and again to pop it .The main advantage of recursion is that it makes the algorithm a little easier to understand or more "elegant".

For finding the factorial we can use For loop that will be good in terms of memory as well as Time Complexity.

int num=4;
int fact = 1;
for (;num>1;num--)
{
fact = fact*num;   
}
//display fact

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM