1

I am trying to get factorial of all the numbers of array(recurArray) using recursion and without loops. I am getting Error "Maximum call stack size exceeded" I think there is some issue with the for loop logic, would be helpful if someone can explain the cause of error and how to fix it

Thanks.

//code

function recur(){
 var n;
 var result;
 if(n == 1)
 return 1;
 var recurArray = [5,6,7,8,9];
 for (var i = 0;i<recurArray.length;i++){
    n = recurArray[i];
    result = n * recur(n-1);
    n=n-1;

 }
 console.log("val of n " + n  + "value of i " + i);
 return result;

}
recur();
Santosh Prasad
  • 59
  • 1
  • 2
  • 8
  • 1
    Your `recur` function does not have any parameters? – Bergi May 12 '17 at 07:50
  • 1
    Yes, you definitely should not use a `for` loop if you don't want to use loops – Bergi May 12 '17 at 07:51
  • Possible duplicate of [Fast factorial function in JavaScript](http://stackoverflow.com/questions/3959211/fast-factorial-function-in-javascript) – Dave May 12 '17 at 15:41

4 Answers4

0

Your recur() function should probably take n as an argument, otherwise n will never be 1 (if(n == 1) return 1;) and your function will keep calling itself until it crashes.

Try function recur(n){ instead.

kalsowerus
  • 998
  • 8
  • 23
0

As you have array, you should use loop.

function recur(x) {
   if(x==0) {
      return 1;
   }
   return x * recur(x-1);
}

function getFact() {
    var recurArray = [5,6,7,8,9];
    for (var i = 0;i<recurArray.length;i++){
      console.log(recur(recurArray[i]));
    }
}

getFact();
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
0

In Each occurence you reset the factorial so it keep rolling for fact(5) you need to have a function that calculate the factorial and an other one for the loop over your array like this :

function recur(n){
   if(n == 1){
      return 1;
   } else {
      return n* recur(n-1);
   }
}


var recurArray = [5,6,7,8,9];
for (var i = 0;i<recurArray.length;i++){
    n = recurArray[i];
    result = recur(n);
    console.log("factorial of n " + n  + " is " + result);
}
Sushii
  • 63
  • 5
0

Try something like this:

function factorial(number) {
var temp;

if(number <= 1) return 1;

temp = number * factorial(number - 1);
return temp;
}

In this case factorial(5); will return !5 . Recursive functions are not supposed to have loops inside(They can, but the execution time would be horrendous). Also recursive functions call themselves with different parameters(otherwise you would overflow the browser stack). In your case you call recursive() an infinite amount of times and the loop always starts from 5 , infinitely. The passed parameter is what stops the recursion.

George Pasquali
  • 328
  • 1
  • 8