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

前端 未结 11 1080
迷失自我
迷失自我 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条回答
  •  情歌与酒
    2020-11-30 09:07

    My favorite solution to this problem is a classic divide and conquer recursive solution. It is actually faster then multiplying n times as it reduces the number of multiplies in half each time.

    public static int Power(int x, int n)
    {
      // Basis
      if (n == 0)
        return 1;
      else if (n == 1)
        return x;
    
      // Induction
      else if (n % 2 == 1)
        return x * Power(x*x, n/2);
      return Power(x*x, n/2);
    }
    

    Note: this doesn't check for overflow or negative n.

提交回复
热议问题