Why is the runtime of this code O(n^5)?

前端 未结 3 1481
猫巷女王i
猫巷女王i 2021-01-21 02:55

I have been asked to determine the big-O time complexity of this code:

function(int n) {
    for (int i = 0; i < n; i++) {
        for (int j = i; j < i *          


        
3条回答
  •  花落未央
    2021-01-21 03:14

    Mathematical form for total time complexity of this question in a worst case is as follow:

    So complexity is O(n^5).

    Edit: In above answer I don't attention to if performance.

    We can change your code as follow:

    function(int n) {
        for (int i = 0; i < n; i++) {
            for (int j = i; j < i * i; j+=i) {
                    for (int k = 0; k < j; k++) {
                        printf("*");
                    }
            }
        }
    }
    

    So,as templatetypedef mentioned, it is evident that total runtime is O(n^4).

提交回复
热议问题