How does this recursion work?

前端 未结 11 571
轮回少年
轮回少年 2020-11-30 11:03

This is an example from Eloquent Javascript:

By starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of

11条回答
  •  眼角桃花
    2020-11-30 11:19

    If you get rid of the pretty printing stuff, the code is a little easier to read:

    function findSequence(goal) {
        function find(start) {
            if (start == goal) {
                return true;
            } else if (start > goal) {
                return false;
            } else {
                return find(start + 5) || find(start * 3);
            }
        }
    
        return find(1);
    }
    

    The outer function, findSequence, dynamically creates a new function called find where goal is taken from the scope of the parent function. You could re-write it like this for clarity:

    function findSequence(start, goal) {
        if (start == goal) {
            return true;
        } else if (start > goal) {
            return false;
        } else {
            return findSequence(start + 5, goal) || findSequence(start * 3, goal);
        }
    }
    

    Now, you can see a little more clearly what happens. The recursive step is in the final return statement, which tries both start + 5 and start * 3 at each step and picks the branch that eventually returns true.

    Follow the logic of findSequence(1, 23) by hand and you'll understand how it works.

提交回复
热议问题