简体   繁体   中英

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) ?

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.

It's 2 raised to the 0 power or 2 0 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM