From http://msdn.microsoft.com/en-us/library/system.math.pow.aspx
int value = 2;
for (int power = 0; power <= 32; power++)
Console.WriteLine("{0}^{1} = {2:N0}",
value, power, (long) Math.Pow(value, power));
Math.Pow takes doubles as arguments, yet here we are passing in ints.
Question: Is there any danger of floating point rounding errors if there is an implicit conversion to double happening?
If yes, it is better to use something like:
public static int IntPow(int x, uint pow)
{
int ret = 1;
while (pow != 0)
{
if ((pow & 1) == 1)
ret *= x;
x *= x;
pow >>= 1;
}
return ret;
}
In your special case, when you are calculating 2 to the power x, you can use a simple left shift. This would simplify your code to:
public static int TwoPowX(int power)
{
return (1<<power);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With