This discussion is archived
6 Replies Latest reply: Jul 20, 2008 9:29 PM by 807589

# Questions with recursion....

Currently Being Moderated
The task at hand is to create a recursive method to compute x^n by using this forumla.

x^0 = 1
x^n = (x^n/2)^2 if n > 0 and even
x^n = x * (x^(n-1)/2)^2 if n > 0 and odd

I just had a couple of questions. I struggle with recursion and I dint know if i used recursion the right way. That was my first question. My code works, but for some reason it seemed easier than I thought. Is it because I just did all my math in one line and returning that same line of code? Or just it seem odd to me because recursion is odd for me to begin with and cannot really see whats going on???/

``````public class Exercise_33 {

public static void main(String[] args) {
double myNumber = powers(2,3);
System.out.print(myNumber);
}

public static double powers(double x , int n){  // 3,5,5
if(n <= 0)
return 1;
else{

if(n % 2 == 0){ // even
return powers(x,n/2) * powers(x,n/2);

}
else{     // odd
if(n <= 1)
return x;
else
return x * (powers(x,(n-1)/2) * powers(x,(n-1)/2));
}
}

}
}``````
• ###### 1. Re: Questions with recursion....
Currently Being Moderated
Have you tested your code? Does it produce correct results?
• ###### 2. Re: Questions with recursion....
Currently Being Moderated
Yes it does work.....did i use recursion the right way???
• ###### 3. Re: Questions with recursion....
Currently Being Moderated
A very basic definition of recursion is a method that calls itself. Your method does that and produces correct results. What more do you want? A pat on the head?
• ###### 4. Re: Questions with recursion....
Currently Being Moderated
I was just curious because when ever I looked up info on the web all the examples were using two methods thats all.

For example one method called powers that would have one parameter and within that method another powers method would be called with 2 different parameters. So i dint know exactly if recursion could be completed with only one method.
• ###### 5. Re: Questions with recursion....
Currently Being Moderated
One motivation of this recursive definition was to be efficient. As such, you might want to replace
``return powers(x,n/2) * powers(x,n/2);``
With
``````int half = powers(x,n/2);
return half*half;``````
And so in the odd case.
• ###### 6. Re: Questions with recursion....
Currently Being Moderated
You have to remember that examples are exactly that, examples. They do not have "THIS IS HOW YOU MUST DO IT" across the top of them.