Understanding How Many Times Nested Loops Will Run

时光怂恿深爱的人放手 提交于 2019-12-03 00:32:10

Consider the loop for (i=1; i <= n; i++). It's trivial to see that this loops n times. We can draw this as:

* * * * *

Now, when you have two nested loops like that, your inner loop will loop n(n+1)/2 times. Notice how this forms a triangle, and in fact, numbers of this form are known as triangular numbers.

* * * * *
* * * *
* * *
* *
*

So if we extend this by another dimension, it would form a tetrahedron. Since I can't do 3D here, imagine each of these layered on top of each other.

* * * * *     * * * *     * * *     * *     *
* * * *       * * *       * *       *
* * *         * *         *
* *           *
*

These are known as the tetrahedral numbers, which are produced by this formula:

n(n+1)(n+2)
-----------
     6

You should be able to confirm that this is indeed the case with a small test program.

If we notice that 6 = 3!, it's not too hard to see how this pattern generalizes to higher dimensions:

n(n+1)(n+2)...(n+r-1)
---------------------
         r!

Here, r is the number of nested loops.

The mathematical formula is here.

It is O(n^3) complexity.

This number is equal to the number of triples {a,b,c} where a<=b<=c<=n.
Therefore it can be expressed as a Combination with repetitions.. In this case the total number of combinations with repetitions is: n(n+1)(n+2)/6

The 3rd inner loop is the same as the 2nd inner loop, but your n is a formula instead.

So, if your outer loop is n times...

and your 2nd loop is n(n+1)/2 times...

your 3rd loop is....

(n(n+1)/2)((n(n+1)/2)+1)/2

It's rather brute force and could definitely be simplified, but it's just algorithmic recursion.

1 + (1+2) + (1+ 2+ 3 ) +......+ (1+2+3+...n)

You know how many times the second loop is executed so can replace the first two loops by a single one right? like

for(ij = 1; ij < (n*(n+1))/2; ij++)
   for (k = 1; k <= ij; k++)
      x = x + 1;

Applying the same formula you used for the first one where 'n' is this time n(n+1)/2 you'll have ((n(n+1)/2)*(n(n+1)/2+1))/2 - times the x = x+1 is executed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!