简体   繁体   English

证明函数的时间复杂度为O(n^3)

[英]Prove that the time complexity of a function is O(n^3)

    public void function2(long input) {
    long s = 0;

    for (long i = 1; i < input * input; i++){
        for(long j = 1; j < i * i; j++){
            s++;
        }
    }
} 

l'm pretty certain that the time complexity of this function is n^3, however if someone could provide a line by line explanation of this, that would be great.我很确定这个函数的时间复杂度是 n^3,但是如果有人可以对此进行逐行解释,那就太好了。

First of all, you need to define what n is if you write something like O(n^3) , otherwise it doesn't make any sense.首先,如果你写O(n^3)类的东西,你需要定义n是什么,否则它没有任何意义。 Let's say n is the value (as opposed to eg the bit-length) of input , so n = input .假设ninput的值(而不是例如位长),所以n = input

The outer loop has k iterations, where k = n^2 .外循环有k次迭代,其中k = n^2 The inner loop has 1^2 , 2^2 , 3^2 , ... up to k^2 iterations, so summing up everything you get O(k^3) iterations (since the sum of the p -th powers of the first m integers is always O(m^(p+1)) ).内部循环有1^22^23^2 、... 最多k^2次迭代,所以总结所有你得到O(k^3)次迭代(因为p幂的总和前m整数总是O(m^(p+1)) )。

Hence the overall time complexity is O(n^6) .因此,整体时间复杂度为O(n^6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM