Understanding How Many Times Nested Loops Will Run

前端 未结 6 1529
野趣味
野趣味 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:48

    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.

提交回复
热议问题