简体   繁体   English

递归除法函数的最坏情况时间复杂度?

[英]Worst-case time complexity of a recursive dividing function?

Given this algorithm:鉴于此算法:

void turtle_down(double val){
    if (val >= 1.0)
        turtle_down(val/2.0);
}

From what I know, T(n) = T(n/2) + O(1).据我所知,T(n) = T(n/2) + O(1)。

O(1) is the worst-case time complexity of the base function which is val != 0.0 (am i getting this right?). O(1) 是基函数最坏情况下的时间复杂度,即 val != 0.0(我做对了吗?)。 And then the recursive call gives a time complexity of T(n/2) since we divide n before the recursive call.然后递归调用给出了 T(n/2) 的时间复杂度,因为我们在递归调用之前除以 n。 Is that right?那正确吗?

But I don't understand how to do the math here.但我不明白如何在这里做数学。 I don't know how will we arrive at O(log n)(base 2).我不知道我们将如何达到 O(log n)(base 2)。 Anyone care to explain or show me the math?有人愿意解释或向我展示数学吗?

void turtle_down(double val){
    if (val != 0.0)
        turtle_down(val/2.0);
}

In the above code, the test condition if (val != 0.0) may not give you the expected result.在上面的代码中,测试条件if (val != 0.0)可能不会给你预期的结果。 It would go into an infinite loop.它会进入一个无限循环。 Consider the case when val=32.考虑 val=32 的情况。 You can see that it will never reach 0 by repeated division with 2.可以看到,通过与 2 重复除法,它永远不会达到 0。

But if you replace the test condition with say if (val >= 1) then recurrence relation for the given function will be T(n) = T(n/2) + O(1).但是如果你用if (val >= 1)替换测试条件,那么给定函数的递归关系将是 T(n) = T(n/2) + O(1)。

In this case the time complexity is T(n) = O(log n).在这种情况下,时间复杂度为 T(n) = O(log n)。

To get this result you can use the Master Theorem.要获得此结果,您可以使用主定理。

To understand the given complexity consider val = 32. You can divide val repeatedly by 2, for 5 times till it becomes 1. Notice that log 32 = 5. From this we can see that the number of calls made to the function is log n .要理解给定的复杂度,请考虑 val = 32。您可以将 val 重复除以 2,进行 5 次,直到变为 1。注意 log 32 = 5。由此我们可以看到对该函数的调用次数为log n .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM