Understanding How Many Times Nested Loops Will Run

前端 未结 6 1542
野趣味
野趣味 2021-02-04 19:24

I am trying to understand how many times the statement \"x = x + 1\" is executed in the code below, as a function of \"n\":

for (i=1; i<=n; i++)
  for (j=1; j         


        
6条回答
  •  灰色年华
    2021-02-04 19:45

    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.

提交回复
热议问题