The usual implementation is something along these lines (cribbed from the wikipedia article):
long power(long x, unsigned long n)
{
long result = 1;
while (n > 0) {
/* n is odd, bitwise test */
if (n & 1) {
result *= x;
}
x *= x;
n /= 2; /* integer division, rounds down */
}
return result;
}
Recursion isn't necessary or (I'd say) particularly desirable, although it can win on obviousness:
long power(long x, unsigned long n)
{
if (n == 0) return 1;
long result = power(x, n/2); // x ^ (n/2)
result *= result; // x ^ (n/2)*2
if (n & 1) result *= x; // x ^ n
return result;
}
Of course in any version you overflow a long pretty quickly. You can apply the same algorithms to your favourite bigint representation, although any bigint library is going to include an integer power function already.
Both versions of the function above return 1 for power(0,0)
. You may or may not consider this a bug.