How to calculate the complexity of a given code

大憨熊 提交于 2020-01-25 10:01:10

问题


Function(int n)
if(n<=2)
 return 1;
for(i=n ; i>n/8 ; i-=n/2)
 for(j=n ; j>2 ; j=j/2)
  syso();
return Function(n/2);

In order to calculate I have done the following : T(n) = T(n/2) + O(1) + 2logn

  • T(n/2): the recursive call to the function.
  • O(1) : the if statement.
  • 2logn: the first "for" will run only 2 times * (the second "for") that will run logn times.

** I have assumed that the second for loop will divide the j by 2 meaning that I will have j/2^k times iterations = logn.

With the same logic the next step: T(n) = (T(n/2^2) + O(1) + 2logN)+O(1) + 2logn Keep on going until the K step: T(n) = T(n/2^k) + O(1) + 2*klogn

From the first "if" statement the function will stop when n <= 2, therefor:
n/2^k =? 2 > k = log(n) - 1.

Now I place the k in the function and I get: T(n) = T(2) + O(1) + 2(logn)^2 - 2logn We know that T(2) = O(1) as it's only doing the "if" statment.

T(n) = O(1) + 2(logn)^2 - 2logn. Assuming all the steps I've done are correct, is the complexity is O((logn)^2)?

Or I have a mistake in my calculations.


回答1:


Here is a derivation to compliment Danielle's numerical experiment.


As Danielle's comment points out, the outer loop only executes twice, once with i = n and once i = n/2. The inner loops don't depend on i which makes things easier.

The loop over j will run precisely floor(log2(n)) times, so, assuming that syso() is O(1):

i.e. your recurrence relation is correct, but the expansion was not.

Applying the stopping condition n <= 2 to find the maximum value of k:

Math notes:

  • A number rounded down differs from its original value by less than 1:

    floor(x) = x + O(1)
    
  • The arithmetic series 1 + 2 + ... + n = n*(n+1)/2.

Applying the above points:

Which is consistent with what the numerical results indicate.



来源:https://stackoverflow.com/questions/55250120/how-to-calculate-the-complexity-of-a-given-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!