Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is time complexity of below code?

For(I=1 ; I<=n ; I++)
{
    For(J=1 ; J<=I ; J++)
        {
             For(K=1 ; K<=n^5 ; K=15 × K)
                 {
                      x=y+z;
                 }
        }  
}

It seems to be O(N^2 log N) according to me, but when i analyzed the k loop, it is not following the Log N, which is confusing me,

like image 921
Garrick Avatar asked Dec 09 '25 04:12

Garrick


2 Answers

It should be O(n^2 log(n)) because the inner loop will be called (n/2)(n+1) times and it will loop log base 15 of n^5 = 5 * log base 15 of n because k grows exponentially in the number of loops.

This results in 5(n^2+n)(log base 15 of n)/2 assignments to x, which is O(n^2 * log(n))

like image 70
Jarred Allen Avatar answered Dec 11 '25 14:12

Jarred Allen


Time complexity of your problem is:

enter image description here

Explanation:

When we say

enter image description here

we mean

enter image description here

not

enter image description here

2 base of log function is coming from divide by 2 in the definitions inside of for loops about binary searching not from the binary nature of computers.

But in your case divide by value is not 2 but 15 because of k = 15 × k definition so the base of log function must be 15 not 2.

You can see the correlation between these with replacing k *= 15 line with k *= 2 and

print n * n * int(math.log(n**5,15) + 1)

line with

print n * n * int(math.log(n**5,2) + 1)

in the given Python Code above. Results will continue to match.

Also because of the quitting of binary base you need to round up log function with nearest integer function:

enter image description here

Python Code:

import math

n = 100
i = 1
while i <= n:
    j = 1
    while j <= i:
        k = 1
        counter = 1
        while k <= n**5:
            x = 1 + 1
            k *= 15
            counter += 1
        #print k
        #print counter
        j += 1
    #print j
    i += 1
#print i

print "\nTime Complexity Prediction:"
print n * n * int(math.log(n**5,15) + 1)

print "\nReal World Result:"
print (i - 1) * (j - 1) * (counter - 1)
print ""

Example results of the program:

For n = 10:

Time Complexity Prediction:
500

Real World Result:
500

For n = 100:

Time Complexity Prediction:
90000

Real World Result:
90000

For n = 1000:

Time Complexity Prediction:
13000000

Real World Result:
13000000

For n = 3000:

Time Complexity Prediction:
135000000

Real World Result:
135000000
like image 28
mertyildiran Avatar answered Dec 11 '25 13:12

mertyildiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!