Finding the Complexity of Nested Loops (Big O)

时间:2016-02-03 03:29:24

标签: big-o time-complexity complexity-theory pseudocode discrete-mathematics

I'm given the following nested loops, and I'm told to find it's complexity.

Where "to" is "<=" In pseudocode:

sum = 0;
for i=1 to n
  for j = 1 to i^2
    if(j (mod i) = 0) then
      for k = 1 to j
        sum++

I know that the outermost loop runs n times, the next loop should run n^2 times, but I have no idea how to calculate the next.

Any help would be greatly appreciated.

1 个答案:

答案 0 :(得分:1)

我们可以使用Sigma表示法分析您的算法。我们注意到了

j (mod i) = 0 <=> j is a multiple of i

我们计算执行sum++语句的次数,不计算未达到内循环的迭代次数;这个案例的可接受程度低于总迭代次数w.r.t的增长(~n^3)。执行内循环的sum++命令。

Sigma符号分析:

Sigma

求和规则(+) is from Wolfram Alpha

因此,O(n^4)描述了算法的渐近行为的上界。