Edgar Kiljak - 6 months ago 38

Javascript Question

Please explain. Line return num * factorialize(num - 1). Assume we have an integer 5 as an argument. Must be 5 * factorialize(5-1) = 5 * 4 = 20. How we getting to 120?

`function factorialize(num) {`

if (num === 0) {

return 1;

}

return num * factorialize(num - 1);

}

factorialize(5)

Answer

Quoting from your question

Assume we have an integer 5 as an argument. Must be 5 * factorialize(5-1) = 5 * 4 = 20. How we getting to 120?

When you were starting with `5 * factorialize(5 - 1)`

, you evaluated 5-1 to be 4 (correct), but then you dropped the call to factorialize that. That's how you were getting 20.

Let's take that `factorialize`

function and step through it.

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

Since 5 was passed into factorialize, the local variable `num`

is not equal to 0. This function then returns `num * factorialize(num - 1)`

. Since `num`

is 5, we'll go ahead and start plugging in numbers.

```
= 5 * factorialize(5 - 1)
```

Now here, we're calling `factorialize`

again, this time passing in 4 (5 - 1). This is still not equal to 0, so let's replace `factorialize(5 - 1)`

with its return value (since `num`

is 4 in this call to factorialize, we'll be returning `4 * factorialize(4 - 1)`

```
= 5 * (4 * factorialize(4 - 1))
```

As with before, we're now calling factorialize again, this time passing in 3.

```
= 5 * (4 * (3 * factorialize(3 - 1)))
```

And so on

```
= 5 * (4 * (3 * (2 * factorialize(2 - 1))))
```

And so forth

```
= 5 * (4 * (3 * (2 * (1 * factorialize(1 - 1)))))
```

Now `factorialize(0)`

returns 1; the if-statement finally evaluates to true. This is the *base case*, a known answer that can be expressed without further using recursion. Substituting that, we get this:

```
= 5 * (4 * (3 * (2 * (1 * 1))))
```

This is mathematically equivalent to

```
= 5 * 4 * 3 * 2 * 1 * 1
```

Which equals

```
= 120
```