Skip to content Skip to sidebar Skip to footer

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){

Solution 1:

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;

Solution 2:

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.

Post a Comment for "Javascript Factorial Recursion"