简体   繁体   中英

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.

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. Let's say n is the value (as opposed to eg the bit-length) of input , so n = input .

The outer loop has k iterations, where 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)) ).

Hence the overall time complexity is O(n^6) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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