What is the most efficient way given to raise an integer to the power of another integer in C?
// 2^3
pow(2,3) == 8
// 5^5
pow(5,5) == 3125
What is the most efficient way given to raise an integer to the power of another integer in C?
// 2^3
pow(2,3) == 8
// 5^5
pow(5,5) == 3125
power()
function to work for Integers OnlyComplexity = O(log(exp))
power()
function to work for negative exp and float base.Complexity = O(log(exp))
Ignoring the special case of 2 raised to a power, the most efficient way is going to be simple iteration.
EDIT: As has been pointed out this is not the most efficient way... so long as you define efficiency as cpu cycles which I guess is fair enough.
more generic solution considering negative exponenet
An extremely specialized case is, when you need say 2^(-x to the y), where x, is of course is negative and y is too large to do shifting on an int. You can still do 2^x in constant time by screwing with a float.
You can get more powers of 2 by using a double as the base type. (Thanks a lot to commenters for helping to square this post away).
There's also the possibility that learning more about IEEE floats, other special cases of exponentiation might present themselves.
I use recursive, if the exp is even,5^10 =25^5.