[英]Calculating time complexity of algorithm
How to calculate time complexity of function f? 如何计算函数f的时间复杂度?
void f(int n)
{
if (n <= 1)
return;
g(n, n / 3);
}
void g(int n, int m)
{
int i = 1;
while (m < n) {
m += i;
i++;
}
f(n / 2);
}
The answer is sqrt(n), but I don't see how... 答案是sqrt(n),但我不知道如何...
Thanks 谢谢
First, note that the the program can be translated now to a single function program, by inlining g(n,m)
in f()
: 首先,请注意,现在可以通过在f()
内联g(n,m)
将该程序转换为单个函数程序:
void f(int n)
{
if (n <= 1)
return;
m = n/3;
while (m < n) {
m += i;
i++;
}
f(n / 2);
}
The inner loop runs in O(sqrt(n))
iteration, because it starts from n/3
, ends with n
, and is increased by 1,2,3,... so if we sum it we get: 内部循环以O(sqrt(n))
迭代运行,因为它从n/3
开始,以n
结尾,并增加1,2,3,...,因此,如果将其相加,我们将得到:
n/3 + (1 + 2 + ... + i) >= n
We need to solve the above equation to find the final value of i
, and we get: 我们需要解决上述方程,以找到i
的最终值,我们得到:
1 + 2 + ... + i >= 2n/3
From sum of arithmetic progression: 从算术级数的总和:
i(i+1)/2 >= 2n/3
From the above inequality, we can conclude that indeed i
is in O(sqrt(n))
. 从上面的不等式, 我们可以得出结论 ,确实i
在O(sqrt(n))
。
So, we can denote the complexity as: 因此,我们可以将复杂度表示为:
T(n) = T(n/2) + O(sqrt(n))
^ ^
recursive step syntatic sugar for some function
which is in O(sqrt(n)).
Now, we can see that: 现在,我们可以看到:
T(n) = T(n/2) + sqrt(n) = T(n/4) + sqrt(n/2) + sqrt(n) = ... =
= sqrt(1) + ... + sqrt(n/2) + sqrt(n)
Let F n be the time complexity of f(n)
and G n,m be the time complexity of g(n,m)
. 令F n为f(n)
的时间复杂度,而G n,m为g(n,m)
的时间复杂度。
G n,m = sqrt(nm) + F n / 2 G n,m = sqrt(nm)+ F n / 2
F n = G n,n/3 = sqrt(nn/3) + F n / 2 = C sqrt(n) + F n/2 F n = G n,n / 3 = sqrt(nn / 3)+ F n / 2 = C sqrt(n)+ F n / 2
So the answer is sqrt(n). 因此答案是sqrt(n)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.