简体   繁体   中英

Is this code O(n) or O(logn)?

It's only checking the for loop 1/3n times, so it's still technically linear I guess? However I don't really understand why it wouldn't be O(logn), because many times a code with O(logn) running time ends up checking around 1/3n. Does O(logn) always divide the options by 2 every time?

int a = 0;
for (int i = 0; i < n; i = i+3)
    a = a+i;

With time-complexity analysis, constant factors do not matter. You could do 1,000,000 operations per loop, and it will still be O(n). Because the constant 1/3 doesn't matter, it's still O(n). If you have n at 1,000,000, then 1/3 of n would be much bigger than log n .

From the Wikipedia entry on Big-O notation :

Let k be a constant. Then:

 O(kg) = O(g) if k is nonzero. 

您的代码具有复杂度O(n), O(n)/3 == a * O(n) == O(n)

It is order of n O(n) and not O(logn) . It because the run time increases linearly with the increase in n

For more information take a look at this graph and hopefully you will understand why it is not logn https://www.cs.auckland.ac.nz/software/AlgAnim/fig/log_graph.gif

运行时间为O(n) (以单位复杂度度量)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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