英文:
Big O notation (Algorithms)
问题
你好,我对大O表示法不太了解,对于以下内容我有困惑,如果有人能够友好地解释一下如何计算,我将不胜感激。
int sum=1;
for(int count=n; count>0; count/=2) {
sum=sum*count;
}
<details>
<summary>英文:</summary>
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
int sum=1;
for(int count=n; count>0; count/=2) {
sum=sum*count;
}
</details>
# 答案1
**得分**: 3
每当`count`被2除,它将是`Theta(log n)`(从`n`到`0`)。因此,它也是`O(log(n))`。
<details>
<summary>英文:</summary>
As each time `count` is divided by 2, it will be `Theta(log n)` (from `n` to `0`). Hence, it is in `O(log(n))` as well.
</details>
# 答案2
**得分**: 1
在第一行中,代码将运行一次,因此对于它,复杂性为O(1)。
在第二行中,一个for循环将运行直到count > 0,我们可以看到它每次循环都会除以2,因此它将无限继续运行。因此,基本上无法对无限循环应用大O表示法。同样,您也不能将大O应用于循环内的代码。因此,如果存在任何O(infinite),那么它可能是一个答案,但实际上不存在。因此,只有当n<=0时,才会执行代码,并且复杂性为O(1)。
<details>
<summary>英文:</summary>
In the first line, the code will run once, so for it, the complexity is 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. So basically, you cannot apply Big O notation on an infinite loop. And so also you cannot apply big O to the code inside the loop as well. So if there exist any O(infinite) then it could be an answer, but it won't exist. So you cannot define time complexity until and unless n<=0. if n<=0 then only the code will run once and complexity will be O(1).
</details>
# 答案3
**得分**: 1
*count* 在每次迭代中减半。如果 `n = 64`:
step1 => count = 64
step2 => count = 32
step3 => count = 16
...
因此,其最坏情况的时间复杂度为 `O(log n)`。
然而,在这种情况下,您的循环体具有恒定数量的操作,因此,最佳情况、最坏情况和平均情况相同,并且:
Ω(log n) = Θ(log n) = O(log n)
<details>
<summary>英文:</summary>
*count* gets halved per each iteration. If `n = 64`:
step1 => count = 64
step2 => count = 32
step3 => count = 16
...
Therefore, its worst case scenario has a `O(log n)` time complexity.
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)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论