Is it OK to use Math.Pow (10, n)?

If both base and exponent are integers you might consider not using Pow. But even in that case Pow is usually better because its more readable. If at least one is a floatingpoint value, use Pow.

If the exponent is 0.5 you should use Sqrt, and if the exponent is a small integer (2,3,4) expressing the formula with multiplications is faster, but less readable.

If you want to implement fast exponentiation with an integer exponent the Square-and-Multiply algorithm and not a simple loop might be what you want. But in most scenarios Pow is still faster.


Math.Pow is better.
Here's a rule of thumb - in 99% of the scenarios, favor built-in functions over custom implementations. This makes your code clearer, saves you lots of work, and reduce chances for errors.

Only when you think of using built-in functions in ways they weren't meant to be used, or when they have severe latency problems (never encountered these scenarios myself, to be honest), should you consider building your own implementation.


For integers, maybe a for loop is faster than Math.Pow which probably deals with floating-point numbers. But I seriously doubt that the difference is significant in your case (even though I do not know it).

But if you work with 32-bit signed integers, then you can only store the values of 10^n for n <= 9. But then you would gain speed (and maybe readability) by storing these nine (ten) powers of ten in an array. This is not hard: they are (1), 10, 100, 1000, ... .

If you need to compute 10^n for larger n, you do need to use floating-point numbers. And then there is no reason whatsoever not to use Math.Pow. This is as fast as it gets, and easily readable.

Tags:

C#

.Net

Math