0

I'm having a hard time understanding the else block. I know it's supposed to raise the base parameter to the exponent parameter. But how does it work?

var power = function(base, exponent){

    if (exponent === 0){
        return 1;
    }
    else{
        return base * power(base, exponent - 1);
    }

};

power(2, 2);
4

2 回答 2

1

for an input power(2/*base*/,2/*exponent*/)

ITERATION 1: Since 2/*exponent*/ is not equal to 0: on the entry, it executes the else part.

hence it should return 2 * power(2,(2-1)/*which is 1*/)

ITERATION 2: again, there is a call to power() function with arguments 2/*base*/ and 1/*exponent*/ power(2,1) is executed in else part : returns 2 * power(2,0)

ITERATION 3: again there is a call to power() function with arguments 2/*base*/ and 0/*exponent*/

Since exponent is 0, it executes the if part and returns 1, which completes the second iteration returning 2 to it. that completes the first iteration returning 4 from it.

于 2012-10-13T22:23:36.223 回答
1
power(base, exponent - 1)

is really just base * power(base, exponent - 1). But if we keep thinking about what is happening in those function calls, we see this:

base * ... pow(base, exponent - n)

Let's try power(2, 4):

2 * (2 * (2 * (2 * (1))))

2 * power(2, 4 - 1);

power(2, 4 - 1) simplifies to

2 * power(2, 3 - 1)

which simplifies to

2 * power(2, 2 - 1)

which simplifies to

2 * power(2, 1 - 1)

and that simplifies to 1 since exponent will be 0. When we put it all together this is what we get:

2 * 2 * 2 * 2 * 1
于 2012-10-13T22:26:12.147 回答