Discussion:
Complexity of While Loop
(too old to reply)
Chris Jones
2011-09-21 15:52:21 UTC
Permalink
*Sorry if this is a duplicate, I am trying to figure it out*

Does anyone know how to explain more in depth how we find the
complexity of a while loop?

Thanks
cs240
2011-09-21 19:14:00 UTC
Permalink
Can you specify the problem in more detail? "A while loop" is a general
term and can be used in so many different kinds of algorithms.

Usually the complexity of a loop is expressed as the sum of the
complexities of each iteration. So to get started, you may want to count
the number of iterations the while loop runs.

Vivian
CS240 Tutor
Post by Chris Jones
*Sorry if this is a duplicate, I am trying to figure it out*
Does anyone know how to explain more in depth how we find the
complexity of a while loop?
Thanks
Chris Jones
2011-09-22 13:21:41 UTC
Permalink
say you have the following code

while n >= 1
n = n/2
end while

I know it is of logarithmic time from class, but I did not
specifically understand how they got to that conclusion. (I think I
made a mistake in my notes)

I am trying to work on Q4 from A1, and I know its true, just having
troubles in some of the proof.

Thanks
cs240
2011-09-22 13:56:07 UTC
Permalink
First of all, the assignment operation inside the loop takes constant time
under the RAM model. So the complexity of this loop depends on the number
of iterations that the loop runs. Following the algorithm, the value of n
goes like this:

n, n/2, n/(2^2), n/(2^3), ..., 1

The loop stops after i iterations when n is 1, that is

n/(2^i) = 1

Solve this equation for i, then you have

i = log n

Therefore the while loop runs log n times, each iteration takes constant
time, therefore the while loop has a complexity of theta of log n.

Vivian
CS240 Tutor
Chris Jones
2011-09-22 19:07:09 UTC
Permalink
Thanks a lot, I get it now!

Loading...