简体   繁体   中英

Finding the computational complexity of nested loops

I'm not sure if I'm doing these problems correctly so I need someone to tell me if I'm wrong.

 for ( i = 0 ; i < n ; i ++ ) 

this is n-0 = n assignment and it's O(g(n)) right?

Okay so know, If I want to get the number of assignments and the O(g(n)) in these questions:

 sum = 0;
 for ( i = 1 ; i < n * n ; j ++)
 {
    for ( j = 1 ; j <= n; j ++ )
    {
        sum += j;
    }
}

what I did was, sum=0 is one assignment and the outer loop is n^2 - 1 assignments and the inner loop is n-1 assignments and finally the sum is 1 assignment

Therefore, the number of assignments is 2+(n^3+1) which gives O(g(n^3))

In this nested loop :

 sum = 0;
 for ( i = 1 ; i <= n; i ++ )
 {
    for ( j = 1 ; j <= 100 ; j++) 
    {
        for ( k = 1 ; k <= n ; k ++ )
        {
            sum += k;
        }
    }
 }

What I did was , sum =0 is 1 assignment then the first loop is 1-n assignments the second loop 99 the last loop 1-n and then the sum = 2

So I got 3+(1+n^2) assignments which give me O(g(n^2))

Is there anything wrong with what I just did?

Your calculations are correct. The only thing might be - sometimes it's important whether it's O(g(n^2)) or O(g( 99 *n^2)). The multiplier becomes not-so-important on large-scaled N values, but at small scales - a constant factor of 99x times the iterations (when not optimized by compiler) might be important.

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