Run-Time complexities of the following functions

208 views Asked by At

I need some help with these functions and if the run-time complexities for it are correct, I'm learning the concepts currently in class and I've looked at videos and such but I can't find any videos explaining these tougher ones, so I'm hoping I can get some help here if I'm doing it right.

sum = 0
for i = 1 to n*n
    for j = 1 to i * i * i
        sum++

For this one I am thinking the answer is O(n^5) because the outer loop is running n^2 times while the inner loop will be running n^3 times and together that'll make n^5

sum = 0
for i = 1 to n^2 // O(n^2) times
   j = i
   while j > 0 //(O(n+1) since the while loop will check one more time if the loop is valid
      sum++
      j = (j div 5)

for this run time I'm assuming its going to run O(n^3 + 1) times since outer loop is running n^2 times and while loop will be n+1 and together thats n^3 + 1.

for i = 1 to n // n times
   for j = 1 to n { // n^2 times
     C[i,j] = 0
     for k = 1 to n // n^3 times?
        C[i,j] = C[i,j] + A[i,k]*B[k,j]

}

so for this one I'm thinking it's O(n^6) but I am really iffy on this one. I have seen some examples online where people will figure the loop to be O(n log n) but I am totally lost on how that is found. Any help would be greatly appreciated!

1

There are 1 answers

0
user58697 On

Your understanding of the first and the third algorithms looks correct. The second, however, is totally off. The inner loop

   while j > 0 //(O(n+1) since the while loop will check one more time if the loop is valid
      sum++
      j = (j div 5)

starts with j being equal to i and divides j by 5 at each iteration, so it runs log(i) times. In turn, i varies from 1 to n^2, and the total execution time is a

    sum[i: 1..n^2] log(i)

By the property of a logarithm this sum is equal to log ((n^2)!). Using Stirling approximation for factorial one obtains the time complexity being O(n^2 log(n^2)) = O(2 n^2 log(n)) = O(n^2 log(n)).