简体   繁体   中英

What is the Big O, upper bound of this code

I'm a little confused, I've been researching Big O time complexity for a few hours now and read all the articles on here.

 int myfunc(int n)
 { int result = 0;
   for (int i = 0; i<n; i++)
     for (int j = i; j>0; j--)
       if (i%j == 0)
         result += j;
   return result;
 }

I have had this piece of code presented to me, and I want to find the upper bound of this code.

Now from what I have learnt thus far, I would presume the upper bound is O(n^2) because this is a nested loop. However because J is linked to I; I'm wondering if this code is actually O(n log n), I have to say I do not fully understand the concept of O(n log n). However I comprehend all the other notations such as...O(1),O(n),O(log n),O(n^2),O(n!).

For every iteration of outer-loop, the inner-loop exactly i times.

When i = 0, the inner-loop runs 0 times.

When i = 1, the inner-loop runs 1 times.

When i = 2, the inner-loop runs 2 times.

...

When i = n-1, the inner-loop runs n-1 times.

So, the total number of times the inner-loop runs = 0 + 1 + 2 + ... + (n-1) = (n*(n-1))/2 = (n^2-n)/2.

Hence, the total number of calculations involved = (n^2 - n) / 2.

So, the time-complexity of the given code = O(n^2).

Inner loop starts iterates i times, and i increases by 1 controlled by the outer loop.

Therefore the inner loop will receive 1 , 2 , 3 , ... , n by the outer loop and iterate, which boils down to the inner loop iterating 1 + 2 + 3 + ... + n = n(n+1)/2

n(n+1)/2 = (n^2)/2 + n/2 . The growth of this function is dominated by n^2 therefore the upper bound can be told as O(n^2) .

Check the simulations which I just run. 在此处输入图片说明

The answer is O(n^2).

Imagine the i variable to be the row number of a matrix, and j to be the column number. Using this loop you are only looking at half of the matrix. This gives you a time complexity of O(0.5n^2), but this is just O(n^2).

To try help you understand O(n log(n)):

An example of an O(log(n)) complexity algorithm is a binary search on a sorted list of numbers. You half the problem set at each comparison by checking the middle element and discarding the half of the list that is clearly above or below the number you are looking at.

Doing that same binary search on n different sets which are all length n would have time complexity O(n log(n)).

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