简体   繁体   English

大 O 符号(算法)

[英]Big O notation (Algorithms)

Hi I am new to Big O Notation and having trouble specifying big O for the following if someone could kindly explain to me how to work it out please嗨,我是 Big O Notation 的新手,如果有人可以向我解释如何解决,则无法为以下指定大 O

int sum=1;
for(int count=n; count>0; count/=2) {
    sum=sum*count;
}

As each time count is divided by 2, it will be Theta(log n) (from n to 0 ).由于每次count除以 2,它将是Theta(log n) (从n0 )。 Hence, it is in O(log(n)) as well.因此,它也在O(log(n))中。

In the first line, the code will run once, so for it, the complexity is O(1).在第一行,代码将运行一次,因此对于它,复杂度为 O(1)。 In second line a for loop will run until count > 0 and we can see that it will be divided by 2 every time loop runs and so it will just go on continuously infinite times.在第二行中,for 循环将运行直到 count > 0,我们可以看到每次循环运行时它将被除以 2,因此它将持续无限次。 So basically, you cannot apply Big O notation on an infinite loop.所以基本上,你不能在无限循环上应用大 O 表示法。 And so also you cannot apply big O to the code inside the loop as well.因此,您也不能将大 O 应用于循环内的代码。 So if there exist any O(infinite) then it could be an answer, but it won't exist.所以如果存在任何 O(infinite) 那么它可能是一个答案,但它不会存在。 So you cannot define time complexity until and unless n<=0.因此,除非 n<=0,否则您无法定义时间复杂度。 if n<=0 then only the code will run once and complexity will be O(1).如果 n<=0,那么只有代码会运行一次,复杂度为 O(1)。

count gets halved per each iteration.每次迭代计数减半。 If n = 64 :如果n = 64

step1 => count = 64
step2 => count = 32
step3 => count = 16
...

Therefore, its worst case scenario has a O(log n) time complexity.因此,其最坏情况的时间复杂度为O(log n)

In this case, however, your loop's body has a constant number of operations, therefore, best, worst, and average case scenarios are same, and:但是,在这种情况下,您的循环主体具有恒定数量的操作,因此,最佳、最差和平均情况是相同的,并且:

Ω(log n) = Θ(log n) = O(log n)

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

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