快速幂算法

201 阅读1分钟

快速幂

将普通求幂的 O(N) 优化成 O(logN)

/**
 * Author:  chenjjia
 * Date:    2022/10/15 21:11
 * Github:  https://github.com/chenjjiaa
 */
public class QuickPow {
    public static void main(String[] args) {
        System.out.println(QuickPow.quickPow(2,10));
    }
    /**
     * @param j j次方
     */
    public static int quickPow(int i, int j) {
        int res = 1;
        int temp = i;
        while (j != 0) { // 每次循环之后,j都右移一位
            if (j % 2 == 1) {
                // 例如2^10,是通过 n^2 * n^8 实现的
                res = res * temp;
            }
            j >>= 1;
            temp *= temp; // 每次循环之后,temp都会变成temp的平方
            // n^1、n^2、n^4、n^8
        }
        return res;
    }
}