这部分代码的Big-O是什么?

时间:2015-10-05 17:10:14

标签: big-o

x = 0;
for (i = 1; i <= n; i = i * 3) // Is big(O) of this statement O(log base 3 n)?
{ 
    if (i % 2 != 0) 
        for (j = 0; j < i; j++) // What will be big(O) of this loop and how?
            x++; 
} 

我读到一个答案,即整体大O将是O(n)。如果这是真的,那么这个代码O(n)的大(O)怎么样?

1 个答案:

答案 0 :(得分:2)

内部循环将对每个i执行i操作,从0到log_3(n)。因此,执行的操作数由this common sum给出。它有一个封闭形式的(log_3(n)+ 1)(log_3(n))/ 2,它是O([log n] ^ 2)