问题
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