简体   繁体   中英

JavaScript Factorial Recursion

In the following script, why does badFactorial blow the stack while goodFactorial works?

function badFactorial(n){
    if( n < 0){
        return 1;
    }
    if(n < 2){
        return n;
    }
    return badFactorial(n * (n-1));
}
function goodFactorial(n){
    if(n < 2){
        return n;
    }
    return goodFactorial(n-1) * n;
}

your creatng an endless loop with

badFactorial(n * (n-1));

it will just keep increasing.

say you passe in 7 . instead of decreasing, youre doing

return badfactorial(7 * 6)

when you want :

return badfactorial(6) * 7;

so change the return to be like youre goodfactorial's ,

badfactorial(n-1) * n;

Because in

badFactorial(n * (n-1)) 

the value of n is increasing always and it will never reach 0. That's why you are getting that error.

While in second case,

return goodFactorial(n-1) * n;

n is decremented each time which is very important for any recursive function.

Always remember in terms of recursive calls, the value of n or any argument must decrease else you will be getting stackoverflow error.

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