styler
styler

Reputation: 16481

can someone help me understand what is happening in this code?

Im struggling to understand what this calculation is return base * power(base, exponent - 1); in the following code. Does base get multiplied with the power function that has the base inside it again?

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

power(2,2);

Does this mean that return base = 2*(2,2-1)?

Upvotes: 0

Views: 90

Answers (3)

Andrzej Doyle
Andrzej Doyle

Reputation: 103787

Does base get multiplied with the power function that has the base inside it again?

Yes, absolutely, and that's how this recursive implementation actually works.

If you expand power(10, 4) for example you get:

power(10, 4)
= 10 * power(10, 3)
= 10 * 10 * power(10, 2)
= 10 * 10 * 10 * power(10, 1)
= 10 * 10 * 10 * 10 * power(10, 0)
= 10 * 10 * 10 * 10 * 1

It should hopefully be clear from this expansion exactly why this is a valid (albeit slow) way to calculate exponents.

Upvotes: 3

Sarfraz
Sarfraz

Reputation: 382686

It is custom implementation of built-in method Math.pow. So these statements output same result:

console.log(power(2,8)); // 256
console.log(Math.pow(2, 8)); // 256

In case you need that, use Math.pow instead.

Upvotes: 1

Joe
Joe

Reputation: 82594

It's 2 raised to the 0 power or 20 which is always 1.

It's a recursive method to calculate the exponents. Although Math.pow works better.

So if the exponent is zero the recursion ends if (exponent === 0) return 1. If the exponent is not zero. Then the method calls itself decrementing the exponent variable.

The magic happens return base * power(base, exponent - 1); once the method return 1; the values are pulled off the stack and multiplied by each other.

This is not the best way to do this.

Upvotes: 2

Related Questions