Question

I already searched everywhere for a solution for my problem, but didn't get one. So what I'm trying to do ist use recursion to find out whats a passed integer variable's base to the power of the passed exponent. So for example 3² is 9. My solution really looks like what I found in these forums, but it constantly gives me a stack overflow error. Here is what I have so far.(To make it easier, I tried it with the ints directly not using scanner to test my recursion) Any idea?

public class Power {
   public static int exp(int x,int n) {        
      n = 3;
      x = 2;

      if (x == 0) {
         return 1;
      }
      else { 
         return n * exp(n,x-1);
      }
   }

   public static void main(String[] args) {                           
      System.out.println(exp(2,3));
   }
}
Was it helpful?

Solution

Well, you've got three problems.

First, inside of the method, you're reassigning x and n. So, regardless of what you pass in, x is always 2, and n is always 3. This is the main cause of your infinite recursion - as far as the method is concerned, those values never update. Remove those assignments from your code.

Next, your base case is incorrect - you want to stop when n == 0. Change your if statement to reflect that.

Third, your recursive step is wrong. You want to call your next method with a reduction to n, not to x. It should read return x * exp(x, n-1); instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top