What does O(log n) mean exactly?

后端 未结 30 2365
执念已碎
执念已碎 2020-11-22 01:19

I am learning about Big O Notation running times and amortized times. I understand the notion of O(n) linear time, meaning that the size of the input affects the g

30条回答
  •  -上瘾入骨i
    2020-11-22 01:42

    I can give an example for a for loop and maybe once grasped the concept maybe it will be simpler to understand in different contexts.

    That means that in the loop the step grows exponentially. E.g.

    for (i=1; i<=n; i=i*2) {;}
    

    The complexity in O-notation of this program is O(log(n)). Let's try to loop through it by hand (n being somewhere between 512 and 1023 (excluding 1024):

    step: 1   2   3   4   5    6    7    8     9     10
       i: 1   2   4   8   16   32   64   128   256   512
    

    Although n is somewhere between 512 and 1023, only 10 iterations take place. This is because the step in the loop grows exponentially and thus takes only 10 iterations to reach the termination.

    The logarithm of x (to the base of a) is the reverse function of a^x.

    It is like saying that logarithm is the inverse of exponential.

    Now try to see it that way, if exponential grows very fast then logarithm grows (inversely) very slow.

    The difference between O(n) and O(log(n)) is huge, similar to the difference between O(n) and O(a^n) (a being a constant).

提交回复
热议问题