Estimated algorithm running time

Solution: The calculation process of the product of two n-order matrices A and B can be described as follows (the calculation result is stored in matrix C), and the calculation time required for the following calculation process can be estimated according to the number of executions of each sentence.

S1:  for(i = 0; i < n; i++){
    
                              // S1行语句被执行(n+1)次

S2:       for(j = 0; j < n; j++){
    
                         // S2行语句被执行n * (n+1)次

S3:            C[i][j] = 0;                                // S3行语句被执行n * n次

S4:            for(k = 0; k < n; k++){
    
                 // S4行语句被执行 n * n * (n+1)次

S5:                 C[i][j] += A[i][k] * B[k][j];     // S5行语句被执行 n * n * n次

S6:            }

S7:        }

S8: }

It takes not only n times to execute a for loop, but the last judgement that does not meet the conditions is also counted. When the three for loops are executed, only those that meet the conditions less than n will go in, so it is n^3 In
summary, if it takes one unit of time to execute each statement (ie O (1)), then after the above calculation is completed, the total time overhead required is approximately:

  [(n+1) + n * (n+1) + n * n + n * n * (n+1) + n * n * n] * O (1) = O (n^3)。
  计算O()看最高位的,其他可以省略

Insert picture description here2^k=n
n>=2^0
so k>=0, k is a positive integer, it must be executed k+1 times
. The result is a geometric sequence, and the result is 2n-1

Insert picture description hereThis is two nested for loops, the
outer for is executed k times
and the inner for is executed j^2 times
1^2 + 2^2 +… + k^2 + (k+1)^2 = (1/ 6) * n(n+1)(2n+1)

Guess you like

Origin blog.csdn.net/weixin_44822939/article/details/104819184