How do you do *integer* exponentiation in C#?

前端 未结 11 1076
迷失自我
迷失自我 2020-11-30 08:26

The built-in Math.Pow() function in .NET raises a double base to a double exponent and returns a double result.

W

11条回答
  •  Happy的楠姐
    2020-11-30 08:55

    A pretty fast one might be something like this:

    int IntPow(int x, uint pow)
    {
        int ret = 1;
        while ( pow != 0 )
        {
            if ( (pow & 1) == 1 )
                ret *= x;
            x *= x;
            pow >>= 1;
        }
        return ret;
    }
    

    Note that this does not allow negative powers. I'll leave that as an exercise to you. :)

    Added: Oh yes, almost forgot - also add overflow/underflow checking, or you might be in for a few nasty surprises down the road.

提交回复
热议问题