The built-in Math.Pow()
function in .NET raises a double
base to a double
exponent and returns a double
result.
What's the best way to do the same with integers?
Added: It seems that one can just cast Math.Pow()
result to (int), but will this always produce the correct number and no rounding errors?
My favorite solution to this problem is a classic divide and conquer recursive solution. It is actually faster then multiplying n times as it reduces the number of multiplies in half each time.
Note: this doesn't check for overflow or negative n.
Here's a blog post that explains the fastest way to raise integers to integer powers. As one of the comments points out, some of these tricks are built into chips.
Use double version, check for overflow (over max int or max long) and cast to int or long?
For a short quick one-liner.
There are no negative exponent nor overflow checks.
A pretty fast one might be something like this:
Note that this does not allow negative powers. I'll leave that as an exercise to you. :)
Added: Oh yes, almost forgot - also add overflow/underflow checking, or you might be in for a few nasty surprises down the road.
I cast the result into int, like this:
In this case, there are no rounding errors because base and exponent are integer. The result will be integer too.