question about recursion..

Code java:

public class Recursion {
public static double power(double a, int n){
double tmp,result,answer;
if(n % 2 == 0){
tmp = power(a, n-1);
result = (tmp*(n/2));
answer = result * result;
return answer;
}
else if (n % 2 == 1){
tmp = power(a, n-1);
result = (tmp*((n-1)/2));
answer = result * result;
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..

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.

Re: question about recursion..