Math.Pow is annoying – so I wrote my own

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:

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!
        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;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s