Search code examples
javaexponent

Understanding How a Method Calculates a Number Raised to a Power


I came across a class that solves an exponent problem but I couldn't wrap my head around how the method raiseToPower() works. This is the line that I don't understand: resultVal = baseVal * raiseToPower(baseVal,exponentVal-1);

What is baseVal being multiplied by? raiseToPower(baseVal,exponentVal-1) doesn't seem like an expression to me. If baseVal == 2, than what is raiseToPower(baseVal,exponentVal-1)?

I know how to solve 2^3 in my head, I struggle to understand the steps baseVal * raiseToPower(baseVal,exponentVal-1) takes to solve the problem. I know that exponentVal is decremented by 1 each time raiseToPower() is invoked, but I still don't understand how it's holding a value that can be multiplied by baseVal.

I understand that this recursive method behaves like a loop.

public class ExponentMethod {
    
   // calculates the result of raising a number to a power
   public static int raiseToPower(int baseVal, int exponentVal) {
      
      int resultVal;    // holds the answer to the exponent problem

      // sets resultVal to 1
      if (exponentVal == 0) {
         resultVal = 1;
      }

      else {
          
          // calculate math problem
         resultVal = baseVal * raiseToPower(baseVal,exponentVal-1);
      }

      // returns when exponentVal == 0
      return resultVal;
   }
   
   public static void main (String [] args) {
      int userBase;
      int userExponent;

      userBase = 2;
      userExponent = 3;
      System.out.println(userBase + "^" + userExponent + " = "
        + raiseToPower(userBase, userExponent));
   }
}

// output
2^3 = 8

I am aware that a pow() method exists for raising a number to a power

Thanks,


Solution

  • The method is using recursion to raise a specific base to a certain power.

    Let us take a simple example of 2^2 and run through the code:

    raiseToPower(2, 2) is called

    resultVal = 2 * raiseToPower(2, 2 - 1) is run

    raiseToPower(2, 1) is called

    resultVal = 2 * raiseToPower(2, 1 - 1) is run

    raiseToPower(2, 0) is called

    Base case is hit and we return 1

    Now we go back up the chain!

    resultVal = 2 * 1 and 2 is returned

    resultVal = 2 * 2 and 4 is returned

    So the end result for 2^2 is 4 as expected.

    Another way to think about this is suppose someone already gave you the answer to 2^2, can you use that to calculate 2^3? Yes, you can simply do 2 * 2^2!

    So: raisePower(2,3) = 2 * raisePower(2,2)

    It is important to also have a base case (when power is 0, like in your example above) so that we don't run into an infinite loop! Hope this helps.