简体   繁体   English

查找嵌套循环的计算复杂度

[英]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? 这是n-0 = n分配,它是O(g(n))对吗?

Okay so know, If I want to get the number of assignments and the O(g(n)) in these questions: 好吧,知道了,如果我想获得这些问题中的作业数量和O(g(n)):

 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 我所做的是,sum = 0是一个分配,外循环是n ^ 2-1-分配,内循环是n-1分配,最后总和是1分配

Therefore, the number of assignments is 2+(n^3+1) which gives O(g(n^3)) 因此,分配数为2+(n ^ 3 + 1),得出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 我所做的是,sum = 0是1分配,然后第一个循环是1-n分配,第二个循环99是最后一个循环1-n,然后和= 2

So I got 3+(1+n^2) assignments which give me O(g(n^2)) 所以我得到3+(1 + n ^ 2)项分配给我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)). 唯一可能是-有时是O(g(n ^ 2))还是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. 在大范围的N值上,乘数变得不再那么重要,但是在小范围内-迭代的99倍常数常数(当未由编译器优化时)可能很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM