Finding the number of times a statement runs

拟墨画扇 提交于 2020-01-07 03:48:13

问题


I am told to figure out the number of times the statement foo runs in the following program. We are assuming that n is an even number.

j = 1;
while( j <= n/2 ) 
{
  i = 1;
  while( i <= j ) 
  {
    foo;
    i++;
  }
  j++;
}

I figured the best way to go about this would be start from the inner loop and work my way outward. We know that i = 1 and inside the inner loop we have i <= j. That means this inner loop runs j times. (This is where I start to get confused) In the outer loop, we see the statement j <= n/2 so that means this outer loop runs n/2 times, right? to count the number of times foo runs, it would be j times n/2, wouldn't it? So foo runs j * (n / 2) times? Is this correct?


回答1:


You are correct that the outer loop runs N/2 times (j increments from 1 to n/2). The inner loop runs j times, so the number of times that foo runs changes with each incremental values of j. If you count the runs, with each "row" being an outer lopo run, the end result looks like a triangle (or bowling pins if center-justified):

N=2

 j
---
 1  .   = one run

N=4

 j
---
 1  .   
 2  ..  = three runs

N=6

 j
---
 1 .
 2 ..
 3 ...  = 6 runs

The next step for you is to write the result as a function of N.




回答2:


As we can see j increments by 1 till n/2, while for every iteration inner while loop runs j times, increment i by 1 to 1-j.

And for every iteration of inner while foo runs 1 time.

For first iteration first iteration j = 1, foo runs 1 time..

For second j=2, foo runs 2 times... For n/2nd iteration j = n/2, foo runs n/2 times..

So foo runs total of

1+2+3+...+ n/2 times
That is n/2 * ((n/2 +1))/2 = n/4 * (n/2 +1) = Θ(n2)



来源:https://stackoverflow.com/questions/35140945/finding-the-number-of-times-a-statement-runs

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