简体   繁体   中英

Is complexity O(log(n) + log(n/2) + log(n/4) + log(n/8) + … + log(2)) = O(log(n))?

As homework, I was asked to write an algorithm in O(log(n)) and I could calculate the complexity of the one I wrote as O(log(n) + log(n/2) + log(n/4) + log(n/8) + ... + log(2)).

I think it's rather O(n) since it's roughly log(n)*O(log(n)) = O(n). But I was not sure about it. I know homework questions are not welcome here, but I really don't know another way to find out what complexity it is. Googling didn't help me.

To specify: n in N and n = pow(2, c), c in N

No, it's not O(log n). It is O((log n) 2 ).

O(log(n) + log(n/2) + log(n/4) + log(n/8) + ... + log(2))
= O(log(n * n/2 * n/4 * n/8 * ... * 2))                    using log multiplication rule
= O(log(n * n * n * ... * n / 2 / 4 / 8 / ... / n))
= O(log(nlog n / 2 / 4 / 8 / ... / n))
= O(log(nlog n / (1 * 2 * 4 * 8 * ... * n/4 * n/2 * n))
= O(log(nlog n / ((1 * n) * (2 * n/2) * (4 * n/4) * ...)    group first and last terms
= O(log(nlog n / (n * n * n * ...))                         since we grouped terms,
= O(log(nlog n / n(log n)/2)                                      we halved the number of terms
= O(log(nlog n) - log(n(log n)/2))                             log division rule
= O(log n.log n) - ((log n)/2).log n)                      log power rule * 2
= O(log n.log n) - (log n.log n)/2)
= O(log n.log n)/2)
= O((log n)2/2)
= O((log n)2)                                              big-O doesn't care about constants

Start with some basic arithmetic:

O(log n/2) = O( (log n) + log(1/2))

The constant can be ignored. Hence:

O(log n / 2) = O(log n)

So, you are adding a bunch of things that are O(log n). How many? Well, about log(n) worth. So, that means that the algorithm is:

O( (log n)^2)

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