Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 415
oRookie Avatar asked Dec 07 '25 17:12

oRookie


2 Answers

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
like image 105
Bernhard Barker Avatar answered Dec 09 '25 22:12

Bernhard Barker


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)
like image 24
Gordon Linoff Avatar answered Dec 10 '25 00:12

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!