Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

```public class Recursion {

public static double power(double a, int n){

if(n % 2 == 0){
tmp = power(a, n-1);
result = (tmp*(n/2));

}
else if (n % 2 == 1){
tmp = power(a, n-1);
result = (tmp*((n-1)/2));

return result;
}

return 1;

}
public static void main (String [] args){
double tmp;
tmp = power(2,10);
System.out.println(tmp);
}
}```
it keeps printing 0...

its supposed to print 2 to the power of 10 but i dont know what im doing wrong..
its supposed to be, if n is even solution would be

a^n = (a^n/2)^2 if n is even
a^n = (a^((n-1)/2))^2 if n is odd.... any comments? thanks..

2. ## Re: question about recursion..

I'm a little surprised that code doesn't result in a stack overflow (it looks like it should from visual inspection).

In a recursive algorithm, you must check for the base case(s) first. I don't see a base case before the recursive call, thus you have infinite recursion.

What's the base case? It's when n=0.

Additionally, I think you're recursive logic a little incorrect.
a^n = (a^(n/2))^2 if n is even
a^n = a*(a^((n-1)/2))^2 if n is odd

Lastly, you're code implementing the recursion calls are off.

You're calling power(a,n-1), but the recursive logic requires a^(n/2), not a^(n-1). This needs to be fixed for both the even and odd cases. Also, that strange multiplication by temp*(...) stuff needs to be removed.

3. ## The Following User Says Thank You to helloworld922 For This Useful Post:

gonfreecks (March 16th, 2011)

4. ## Re: question about recursion..

that helped thank you