Understanding How Many Times Nested Loops Will Run

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

    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.

提交回复
热议问题