Oh, okay, I didn't realise you had to do it that crazy way.
![Silly [:p]](/Emoticons/silly.gif)
[code]float power(int x, int n)
{
if (n == 0)
{
if (x == 0) return Float.NaN;
return 1;
}
if (x == 0) return 0;
if (n < 0) return 1 / power(x, -n);
if (n % 2 == 0)
{
return power(x, n / 2) * power(x, n / 2);
}
return power(x, n/2) * power(x, n/2) * x;
}[/code]
This would be my first implementation. You got the most part, but you incorrectly multiply by x in stead of the power function. Oh, you don't need all those
elses by the way, since if you didn't reach that
else you already returned from the function.
Of course this can easily be simplified a bit:
[code]float power(int x, int n)
{
if (n == 0)
{
if (x == 0) return Float.NaN;
return 1;
}
if (x == 0) return 0;
if (n < 0) return 1 / power(x, -n);
float root = power(x, n / 2);
if (n % 2 == 0) return root * root;
return root * root * x;
}[/code]
If must admit though, that since this method reduces the argument by a factor of two each time, it only calls itself 1 + lg n times, which is a lot less than the iterative method, which calls itself n times.
It effectively does a binary search on the problem, which is of course a lot faster than a linear search.