Reputation: 373
This is a hw assignment. The answer/output I want is correct. I just don't understand why. I want the output to be true if the power function matches the number I am checking against. I do get the answer true for these examples, but I don't understand how this recursive function is working.
In the else of this function, I am saying base * the function itself. what does that even represent? How can base * power(base, exponent - 1);
even compute? Shouldn't it just run in a circle and then finally end?
console.log(power(2,4) === 16);
console.log(power(2,3) === 8);
console.log(power(2,2) === 4);
var power = function(base, exponent) {
if(exponent === 0) {
return 1;
}
else {
return base * power(base, exponent - 1);
}
};
Upvotes: 4
Views: 237
Reputation: 2285
For the example of power(2,4), we have
So it goes back through the calls and comes to 2*power(2,0) which we know power(2,0) == 1. That returns as 2. Then it goes back to 2*power(2,1) and we know power(2,1) == 2 since [2*power(2,0)]. This returns as 4.
See the pattern? And so on until we get back to 2*power(2,3) ==16 since we have power(2,3) == 8 since [power(2,2) * power(2,1) * power(2,0) * 1]. Hope this helped!
Upvotes: 0
Reputation: 490423
The exponent is being reduced with each recursive call until it is equal to 0
where it will return a constant 1
, and the function stops being recursive.
Also, if this wasn't homework, there is Math.pow()
:)
Upvotes: 0
Reputation: 61520
The function power returns an integer, so when the function returns base * <some_integer>
is a perfectly valid expression. The best way to trace these things is with a pen and paper:
call stack of power(2,4):
power(2, 4) = 2 * power(2, 3)
power(2, 3) = 2 * power(2, 2)
power(2, 2) = 2 * power(2, 1)
power(2, 1) = 2 * power(2, 0)
power(2, 0) = 1 <--base case
now all you have to do is substitute the values up the call stack
power(2, 4) = 2 * 8 = 16
power(2, 3) = 2 * 4 = 8
power(2, 2) = 2 * 2 = 4
power(2, 1) = 2 * 1 = 2
Upvotes: 5
Reputation: 8125
It might help to write the function using Javascript's syntactic sugar declaration style:
console.log(power(2,4) === 16);
console.log(power(2,3) === 8);
console.log(power(2,2) === 4);
function power(base, exponent) {
if(exponent === 0) {
return 1;
}
else {
return base * power(base, exponent - 1);
}
};
If you want, you can also add the line
console.log("power("+base+", "+exponent+")");
at the head of the function, to watch the recursive call sequence.
Upvotes: 0