N
N
name1e552018-12-19 11:49:55
JavaScript
name1e55, 2018-12-19 11:49:55

Factorial recursion on a simple example?

<script>
alert(fact(5));

function fact(num){
    return (num < 2) ? true :
    num * fact(num - 1);
    } </script>

Why, during three iterations, the values ​​20,60,120 are assigned to the num variable?
That is why, the script understands num * fact(num - 1) as num *= fact(num - 1).
The logic of such behavior interests.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Fedoryan, 2018-12-19
@name1e55

fact(5)
num = 5
5 * fact(5 - 1)
     num = 5 - 1 = 4
     4 * fact(4 - 1)
          num = 4 - 1 = 3
          3 * fact(3 - 1)
               num = 3 - 1 = 2
               2 * fact(2 - 1)
                    num = 2 - 1 = 1 (< 2)
                    return true
5 * 4 * 3 * 2 * true = 120, т.к. true в данном случае приравнивается к 1

And numdon't act likenum *= fact(num - 1)

A
Alexey, 2018-12-19
@Azperin

It just goes on recursion. I think it's worth googling about stacks.

5 * 4 * 3 * 2 * 1 = 20 * 3 * 2 * 1 = 60 * 2 * 1 = 120 * 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question