Calculating powers of integers

前端 未结 16 2008
情书的邮戳
情书的邮戳 2020-12-08 06:18

Is there any other way in Java to calculate a power of an integer?

I use Math.pow(a, b) now, but it returns a double, and that is usually a

16条回答
  •  自闭症患者
    2020-12-08 06:44

    A simple (no checks for overflow or for validity of arguments) implementation for the repeated-squaring algorithm for computing the power:

    /** Compute a**p, assume result fits in a 32-bit signed integer */ 
    int pow(int a, int p)
    {
        int res = 1;
        int i1 = 31 - Integer.numberOfLeadingZeros(p); // highest bit index
        for (int i = i1; i >= 0; --i) {
            res *= res;
            if ((p & (1< 0)
                res *= a;
        }
        return res;
    }
    

    The time complexity is logarithmic to exponent p (i.e. linear to the number of bits required to represent p).

提交回复
热议问题