Trouble Finding Big O Time for this loop

2019-06-28 03:53发布

I'm trying to find the Big O running time for the following code snippet:

for( i = 0; i < n * n; i++ )
    for( j = 0; j < i; j++ )
        k++;

I'm not sure if it would be O(n^3) because of the multiplication of n, or just O(n^2). Some help would be appreciated :)

标签: big-o
3条回答
再贱就再见
2楼-- · 2019-06-28 04:17

A precise and formal way to find out the number of iterations of your algorithm:

enter image description here

查看更多
We Are One
3楼-- · 2019-06-28 04:25

for(i := 1 -> n ){
 for(j := 1 -> i ){
  something
 }
}

runs in O(n^2)[innermost loop runs 1,2,3....n times as the value of n increases, so in total it runs for a sum of 1+2+3...+n = O(n^2)]

in your sample code let i := 1 -> p where p = O(n^2) then since the code runs in O(p^2) its running time will be O(n^4)

Using the Big-O notation can help you through some situations. Consider this :
for(i =n/2; i < n; i++){
 for(j = 2; j < n; j=j*2){
  something
 }
}

the outer loop runs O(n) and the inner loop runs O(log(n))[ see it as constantly dividing n by 2 : definition of log]
so the total running time is : O(n(logn))

查看更多
迷人小祖宗
4楼-- · 2019-06-28 04:38

The inner loop will execute exactly 0 + 1 + ... + n^2 - 2 + n^2 - 1 = (n^2)(n^2 - 1)/2 times (see Arithmetic Series), so it's actually O(n^4).

查看更多
登录 后发表回答