0

I came across an exercise on freecodecamp that required writing a code that would return the factorial for a given integer and gave this example: For example: 5! = 1 * 2 * 3 * 4 * 5 = 120f.

I get how the math works but I couldn't really wrap my head around how to code it until I found something here, n stackoverflow, but without an explination of why it works, that resembled this:

function factorialize(num) {
  if(num === 0) {
    return 1;
  } else {
    return num * factorialize(num - 1);
  }
}

factorialize(5);

I don't really understand how this is iterating through all the integers that are less than or equal to num. Can anybody help explain this to me?

Geraurd D
  • 9
  • 5

4 Answers4

2

It's a recursive function.

Calling factorialize with 5 does the following:

Is 5 equal to 0? No, so then:

return num * factorialize(num - 1); 

Substituting 5 for num means it is actually returning:

5 * factorialize(5-1)

So we can simplify that to

5 * (factorialize(4))

Which then must call factorialize on the second half of the statement to computer the return value.

So you can imagine, factorialize is called again with num = 4. Since num is not equal to zero, it also returns the same num * factorialize(num-1). The original statement is now:

5 * (4 * factorialize(3))

and so it must call itself again... and again... until we have

5 * 4 * 3 * 2 * 1 * factorialize(0)

which then actually returns a single number - this is called a base case so it doesn't infinitely recurse on itself. It returns 1.

Resulting in

5 * 4 * 3 * 2 * 1 * 1

I would argue the base case should be if (num == 1). Either way it works

Edit based on comment: The 0 makes sense, it obviously now covers 0 factorial. Thanks! With the base case of num == 1 it would only work for factorialize with a parameter num > 0.

Diesel
  • 5,099
  • 7
  • 43
  • 81
0

It is called recursion. The basic idea is a function calling itself but passing in a value that gets closer and closer to base can which ends the process. See here: https://en.wikipedia.org/wiki/Recursion_(computer_science) and here: Understanding recursion for more info.

Community
  • 1
  • 1
MrMadsen
  • 2,713
  • 3
  • 22
  • 31
0

It's using something called recursion. Put simply, recursion is what happens when a function calls itself. So in the example, num gets decremented every time it is passed to factorialize, and num gets multiplied by the number passed to factorialize. Try adding a print statement in the else block to see that the number is being decremented with each call

blasko
  • 690
  • 4
  • 8
0

This is a basic implementation of what is known as a recursive function.

https://en.wikipedia.org/wiki/Recursion_(computer_science)

Recursion works by basically having a function call itself. So we are multiplying num * (num-1) all the way to 0 (which returns 1).