Fast Power and Matrix Fast Power Analysis and Code Implementation

foreword

In the ninth lecture of Acwing c++ Lanqiao Cup Tutoring Course, the complex DP- AcWing 1303. The first n items of Fibonacci and the matrix fast power algorithm are used from time to time. Here, I will record the knowledge points and integrate the fast power part. .

The current article has been included in the blog file directory index: blog directory index (continuously updated)

1. Understand the fast power

The fast power is the nth power of the fast calculation base. Its time complexity is O(log₂N), and the efficiency has been greatly improved compared with the simple O(N).

The question leads to: how to count 7 to the 10th power faster?

principle

The core idea of ​​the fast power algorithm is that each step divides the exponent in half, and the corresponding base is squared. In this way, not only can the very large exponent be continuously reduced, but also the number of loops that need to be executed is also reduced, but the final result remains unchanged.

//可以看到由原先的n次倍数相乘之后转变来让运行次数大大减小
3^10=3*3*3*3*3*3*3*3*3*3
3^10=(3*3)*(3*3)*(3*3)*(3*3)*(3*3)
3^10=(3*3)^5
3^10=9^5
9^5=9^4*9^19^5=6561^1*(9^1)

By using fast exponentiation, the time complexity can be reduced to log2N


2. Quick power idea and code

The core dichotomy idea: split into three cases, ①n is an odd number. ②n is an even number. ③n=0.

image-20220418194312084

/**
 * @ClassName 快速幂
 * @Author ChangLu
 * @Date 4/18/2022 7:28 PM
 * @Description 快速幂求解
 */
public class 快速幂 {
    
    

    //取模操作(对大素数取模)
    private static final long MOD = 1000000007;

    public static void main(String[] args) {
    
    
//        System.out.println(qpow(2, 3));
        System.out.println(qpow2(2, 100000000));
    }

    /**
     * 递归快速幂
     * @param a 实数a
     * @param n 阶数n,三种情况,n=0,n=奇数,n=偶数
     * @return
     */
    public static long qpow(long a, long n){
    
    
        if (n == 0){
    
    
            return 1;
        }else if ((n & 1) == 1) {
    
      //奇数
            return qpow(a, n -1) * a % MOD;
        }else {
    
    
            long temp = qpow(a, n / 2) % MOD;
            return temp * temp % MOD;
        }
    }

    /**
     * 非递归方式
     */
    public static long qpow2(long a, long n) {
    
    
        long ans = 1;
        while ( n != 0) {
    
    
            if ((n & 1) == 1) {
    
     //若是n为奇数
                ans *= a % MOD;
                ans %= MOD;//求模处理
            }
            a *= a % MOD; //这个就表示偶数情况
            a = a % MOD;//求模处理
            n = n >> 1;
        }
        return ans;
    }


}

3. Matrix fast power

3.1, matrix multiplication code implementation

First understand the matrix multiplication:

image-20230129171016240

template:

//i与j来进行用来定位结果矩阵中的下标  k则是用来使用第i列数字*第j列数字
for (int i = 0; i <= 2; i ++ ) 
  for (int j = 0; j <= 2; j ++ ) 
  	for (int k = 0; k <= 2; k ++ )
  	  c[i][j] += a[i][k] * b[k][j];

Test code:

import java.util.Arrays;

public class Main {
    
    

    static final int[][] a = {
    
    
            {
    
    1, 2},
            {
    
    3, 4}
    };
    static final int[][] b = {
    
    
            {
    
    3, 1},
            {
    
    2, 4}
    };

    //矩阵乘法
    //返回的是a*b矩阵的结果矩阵
    public static int[][] multi(int a[][], int b[][]) {
    
    
        int x = a.length, y = b[0].length, z = b.length;
        int[][] ans = new int[x][y];
        for (int i = 0; i < x; i++)
            for (int j = 0; j < y; j++)
                for (int k = 0; k < z; k++)
                    ans[i][j] += a[i][k] * b[k][j];
        return ans;
    }

    public static void main(String[] args) {
    
    
        //矩阵乘法
        int[][] c = multi(a, b);
        for (int[] arrs : c) {
    
    
            System.out.println(Arrays.toString(arrs));
        }
    }
}

image-20230129172719510


3.2, matrix fast power code implementation

If the matrix is ​​A, let us find A n. At this time, if we can realize the fast exponentiation of the matrix, the code template is as follows:

//n表示的乘的次数
while (n != 0) {
    
    
    //n为奇数情况
	if ((n & 1) == 1) ans = mult(ans, A);
    //n为偶数情况
	mult(A, A);
	n >>= 1;
}

Actual Example Code: Matrix Fast Exponentiation

import java.util.Arrays;

public class Main {
    
    

    static final int[][] a = {
    
    
            {
    
    1, 2},
            {
    
    3, 4}
    };
    static final int[][] b = {
    
    
            {
    
    3, 1},
            {
    
    2, 4}
    };

    //矩阵乘法
    //返回的是a*b矩阵的结果矩阵
    public static int[][] multi(int a[][], int b[][]) {
    
    
        int x = a.length, y = b[0].length, z = b.length;
        int[][] ans = new int[x][y];
        for (int i = 0; i < x; i++)
            for (int j = 0; j < y; j++)
                for (int k = 0; k < z; k++)
                    ans[i][j] += a[i][k] * b[k][j];
        return ans;
    }

    //矩阵快速幂
    public static int[][] pow_multi(int a[][], int n) {
    
    
        int m = a.length;
        //初始化ans结果矩阵
        int ans[][] = new int[m][m];
        for (int i = 0; i < m; i ++) {
    
    
            for (int j = 0; j < m; j ++) {
    
    
                if (i == j) ans[i][j] = 1;
            }
        }
        //写法基本与整数快速幂一致
        while (n != 0) {
    
    
            if ((n & 1) == 1) ans = multi(ans, a);
            a = multi(a, a);
            n >>= 1;
        }
        return ans;
    }

    public static void main(String[] args) {
    
    
        //矩阵乘法
        int[][] c = multi(a, b);
        for (int[] arrs : c) {
    
    
            System.out.println(Arrays.toString(arrs));
        }
        System.out.println();
        //快速幂
        int[][] d = pow_multi(a, 2);
        for (int[] arrs : d) {
    
    
            System.out.println(Arrays.toString(arrs));
        }
    }
}

image-20230129175125566

References

[1]. Lanqiao Cup software competition preparation: fast power and matrix fast power

[2]. How to calculate fast power in "Algorithm Knowledge" (Part 1) : Fast Power.

[3]. Algorithm Study Notes (4): Quick Power : This article is good and can be learned.

Guess you like

Origin blog.csdn.net/cl939974883/article/details/128793342