Here's how you can approach it. Find the statements that run in constant time (I'll do the second one for you, you can do the rest).
The constant time statements are:
x = x + j/float(i*(i+1))
What I mean by that is that they take the same amount of time no matter what the value of n
is.
Now you need to figure out how n
affects that constant time. Since you're running inside a loop 1..n
which is itself running inside a loop 1..n
, the constant time statements will execute n * n
times. Hence the complexity is O(n*n)
. You figure this out by asking yourself how the input value n
affects the running time.
Armed with that, the first one should be a walk in the park for you. The third one may end up being so difficult that you would prefer to trip over a log and land flat on your face.
There's a hint in there and it's not the word "face".
As to what the code accomplishes in each case, you should run it, after inserting suitable print
statement inside the loop to show you how affected variables change each time through.
For example, part 3 will start x
at 1
and double it until it's greater than or equal to n
. You don't have to be a rocket scientist to figure out this will give you the smallest power of two that's greater than or equal to n
. But, by all means, test it (with different values of n
below):
n = 127
x = 1
while x < n:
print x
x = x * 2
print x
To get running time, you have to either have a very fine grained measuring tool or you have to run it many times. If you're on Linux, you can use the time
command:
$ time python qq.py
128
real 0m0.107s
user 0m0.030s
sys 0m0.093s
You should run it ten times for each input value, throw away the fastest and slowest and average the other 8. This will give you a reasonable average, without outliers.