简体   繁体   中英

javascript recursive function - not understanding what is going on

I was reading javascript documentation on 'functions' and came across this code that I am not following how it's working step by step, specifically the inner recursive function.

function factorial(n){
  if ((n == 0) || (n == 1))
    return 1;
  else
    return (n * factorial(n - 1));
}

var a, b, c, d, e;
a = factorial(1); // a gets the value 1
b = factorial(2); // b gets the value 2
c = factorial(3); // c gets the value 6
d = factorial(4); // d gets the value 24
e = factorial(5); // e gets the value 120

I am not following the logic beyond the first if statement. Could someone spell it out. I have already ran the code and works just as specified.

For example, let's calculate factorial(4) :

  • n = 4
  • Since n != 0 and n != 1 , the value of factorial(4) is 4 * factorial(3)
  • Let's calculate factorial(3)
    • n = 3
    • Since n != 0 and n != 1 , the value of factorial(3) is 3 * factorial(2)
    • Let's calculate factorial(2)
      • n = 2
      • Since n != 0 and n != 1 , the value of factorial(2) is 2 * factorial(1)
      • Let's calculate factorial(1)
        • n = 1
        • Since n == 1 , the value of factorial(1) is 1
      • Therefore, the value of factorial(2) is 2 * 1 == 2
    • Therefore, the value of factorial(3) is 3 * 2 == 6
  • Therefore, the value of factorial(4) is 4 * 6 == 24

If the passed parameter is 0 or 1, 1 is returned.

If the passed parameter is 2, then the parameter (2) multiplied by a recursion of the same function being passed 1, since it's passed 1, 1 is returned, as above.

If the parameter passed is 3, then it becomes 3 * 2 * 1, the latter two being resolved through recursion.

For 4, then it becomes 4 * 3 * 2 * 1, the latter 3 being resolved through recursion.

Thus if you were wondering what 100 * 99 * 98..... * 3 * 2 * 1 equaled, this function could provide the answer.

The point of the if statement, of course, is to make sure that factorial(1 - 1) never happens, because if it did, the last step would be * 0, making the result always 0.

As @Oriol points out in reply to me (and in their own answer), the point is also (but primarily) to make sure the recursion stops, otherwise it would continue to negative infinity (or rather, system crash).

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