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

Questions with recursion....

807589 Newbie
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));
               }
       }
     
     }
}