Please help me understand this recursive function...
var stack = Array;
function power(base, exponent){
if ( exponent === 0 ) {
return 1;
} else {
stack[exponent-1] = base * power(base, exponent - 1);
return stack[exponent-1];
}
}
I dont understand what
stack[exponent-1] is doing
4 Answers 4
Which one? It's called twice. But each time it's either getting the value that exists in the array at the index equal to the current value of exponent-1 or setting that value.
It's just an array index and access.
1 Comment
exponent = 5, so that call translates into stack[4], accessing the fifth element of the array (array indexes start at 0). Mozilla documentation for array. They're both identical in nature, just one of them sets a value (the one with the =) and one of them gets a value.I did console log of stack[exponent-1] using
var stack = Array;
function power(base, exponent){
if ( exponent === 0 ) {
return 1;
} else {
stack[exponent-1] = base * power(base, exponent - 1);
console.log(stack[exponent-1]);return stack[exponent-1];
}
}
O/P:
power(2,5)
2
4
8
16
32
So function class recursively until exponent become 0 (nth call), then it will start returning results
first it will return 1 (because exponent is 0)
then returns 2 * 1 (return of n call)
then 2 * 2 (return of n-1 call)
then 2 * 4 (return of n-2 call) and so on
2 Comments
The algorithm is stacking the result of each power from the initial exponent to 0.
If you run power(2, 3), the stack will, at some point, be:
stack[2] = 8
stack[1] = 4
stack[0] = 2
This really has nothing to do with the mathematic concept of power.
3 Comments
have a look on this version!
function pow(x,n)
{
return n==0?1:n==1?x:n==2?x*x:pow(pow(x,(n-n%2)/2),2)*(n%2==0?1:x);
}
can get it shorter?
^is exclusive or, not power.)