作为家庭作业,我被要求在O(log(n))中编写一个算法,我可以计算我写的那个复杂度为O(log(n)+ log(n / 2)+ log(n) / 4)+ log(n / 8)+ ... + log(2))。
我认为它相当于O(n),因为它大致是log(n)* O(log(n))= O(n)。但我不确定。我知道家庭作业问题在这里不受欢迎,但我真的不知道另一种方法来找出它的复杂程度。谷歌搜索并没有帮助我。
指定:n为N,n = pow(2,c),c为N
答案 0 :(得分:6)
不,它不是O(log n)。它是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
答案 1 :(得分:1)
从一些基本算术开始:
O(log n/2) = O( (log n) + log(1/2))
常量可以忽略。因此:
O(log n / 2) = O(log n)
所以,你要添加一堆O(log n)。多少?好吧,关于log(n)值得。所以,这意味着算法是:
O( (log n)^2)