简体   繁体   English

计算大O符号

[英]Calculate Big O Notation

I currently have the following pseudo code, and I am trying to figure out why the answer to the question is O(n). 我目前有以下伪代码,并且我试图找出问题的答案为什么是O(n)。

sum = 0;
for (i = 0; i < n; i++) do
    for (j = n/3;j < 2*n; j+= n/3) do
        sum++;

I thought the answer would be O(n^2) since the first for loop would run 'n' times and the second for loop has += n/3, giving it another (n divided by something times), which would just simplify to O(n^2). 我认为答案将是O(n ^ 2),因为第一个for循环将运行'n'次,第二个for循环具有+ = n / 3,给它另一个(n除以某时间),这将简化到O(n ^ 2)。 Could somebody explain why it is O(n)? 有人可以解释为什么它是O(n)吗?

This is because the second loop runs in constant amount of operations (does not depend on n ). 这是因为第二个循环以恒定的操作量运行(不依赖于n )。 From n/3 to 2n with a step n/3 which is similar to from 1/3 to 2 with a step 1/3 . n/32n ,步长为n/3 ,类似于从1/32 ,步长为1/3

This will run 5-6 times for reasonable n (not 0) (the number is not important and depends on how do you calculate / ) 对于合理的n (不是0),它将运行5-6次(该数字并不重要,取决于您如何计算/

The inner loop increments by a multiple of n , not by 1, so its runtime is bounded by a constant (6?). 内部循环以n的倍数递增,而不是1的倍数,因此其运行时以常数(6?)为界。 So the total number of steps is bounded by a constant multiple of n (namely 6 n ). 因此,总步数由n的常数倍(即6 n )限制。

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

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