-1

I am trying to create a simple recursive JavaScript function that produces factorials. I think I exhaust local memory in the callstack when running the code below and likely trigger an infinite recursion.

*Note: I want to use recursion to solve it.

function factorial(num, factor) {
  //loop through descending order multiply
  if (num === 1) {
    return newNum
  }
  let newNum = num --;
  let newProduct = num * newNum;
    //recurse
  return factorial(newNum, newProduct);
}

// Test cases
console.log(factorial(4)); // -> 24
console.log(factorial(6)); // -> 720
console.log(factorial(0)); // -> 1

Any suggestions as to how and why I should modify my above code.

Codestudio
  • 525
  • 3
  • 5
  • 28
  • Does this answer your question? [How would you write a non-recursive algorithm to calculate factorials?](https://stackoverflow.com/questions/231250/how-would-you-write-a-non-recursive-algorithm-to-calculate-factorials) – HaroldH Jul 11 '20 at 21:57
  • No, because I want to use recursion to solve it. – Codestudio Jul 11 '20 at 21:58
  • Your base case should be `num < 0` not `num === 1` if you want it to work on `0` input – Bergi Jul 11 '20 at 22:00
  • 1
    `return product`. What product? – Christian Jul 11 '20 at 22:00
  • 1
    I don't get it. Where is the parameter 'factor' used in factorial? newNum is not defined either, that seems like bad practice. – D. Foley Jul 11 '20 at 22:03
  • 1
    Does this answer your question? [JavaScript Factorial Recursion](https://stackoverflow.com/questions/27318492/javascript-factorial-recursion) – Heretic Monkey Jul 11 '20 at 22:04
  • No, because I'm not differentiating between "bad" or "good" factorial types. – Codestudio Jul 11 '20 at 22:32

1 Answers1

1

You are a problem with your decrement : That’s because the original value of the operand is being returned prior to the operand being changed(you need to change num-- by --num). Can you look this https://codeburst.io/javascript-increment-and-decrement-8c223858d5ed. You xan change your code by this

function factorial(num, factor=1) {
  //loop through descending order multiply
  if (num <= 1) {
    return factor
  }

  let newProduct = factor * num--;
    //recurse
  return factorial(num, newProduct);
}
Omar Sy
  • 486
  • 2
  • 8
  • Thank you. This solves the first two test cases. But for the last test case where input is 0 it still returns: "Range Error: Maximum call stack size exceeded" – Codestudio Jul 11 '20 at 22:26
  • Does newProduct take the place of factor=1 after the first iteration? I'm trying to make sense of the code to see exactly how the multiplied values are being saved in the parameter between each step in the loop. – Codestudio Jul 11 '20 at 22:45