If you’ve not had to use it yet, Math.Pow() is annoying.

What it does: finds the ‘Power of’ x. So 2^2=4, 2^4=16, etc.

Why it’s annoying:

Well, there are a number of reasons. The first is it’s not the ^ symbol which is widely used by many programming languages (but not .Net).

The second is it requires decimal as it’s input type. Why MS? Why? I wanted to use the ulong datatype in my project but couldn’t get the power of it without converting it to decimal first. With large numbers this has the annoying feature of being expressed with .Nets exponential syntax like so:

1.2345678901230000E-030

I was working on a project that required me to calculate very large whole numbers and then write them to a file, this was an issue.

So, what I did was make it better by re-writing Math.Pow using ulong. I’m sure there are other ways to do this, but re-writing this function proved really simple to do. Feel free to use my method in your projects (though leaving a reference in the code to me would be nice!), also feel free to post alternative ways to solve this problem. I always enjoy your feedback!

//Pow() taken from Anthony's Tech Blog!
//https://anthonystechblog.wordpress.com/2011/04/18/math-pow-is-annoying/
static ulong Pow (ulong x, ulong y)
{
if (y == 0) return 1;
ulong count = x;
for (ulong i = 0; i < y-1; i++)
{
count = x * count;
}
return count;
}

### Like this:

Like Loading...

*Related*