I need to compute power (10, n)
Is it OK to use Math.Pow (10, n)?
Or should I use a loop?
for (int i = 0; i < n; i++){
x*=10;
}
Which one is better? and why?
I need to compute power (10, n)
Is it OK to use Math.Pow (10, n)?
Or should I use a loop?
for (int i = 0; i < n; i++){
x*=10;
}
Which one is better? and why?
There are way more performant implementations of integer Pow, than multiplying by 10 in a loop.
See this answer, for example, it also works for other base values, not just 10.
Also, consider caching results, up until a reasonable amount, in an array.
Here's my recent code, for a reference:
private static readonly Int64[] PowBase10Cache = {
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000,
100000000000000000,
1000000000000000000,
};
public static Int64 IPowBase10(int exp)
{
return exp < PowBase10Cache.Length ? PowBase10Cache[exp] : IPow(10L, exp);
}
public static Int64 IPow(Int64 baseVal, int exp)
{
Int64 result = 1;
while (exp > 0)
{
if ((exp & 1) != 0)
{
result *= baseVal;
}
exp >>= 1;
baseVal *= baseVal;
}
return result;
}