Got a question on this step count problem. I think I have the basic idea but struggling to get the math straight on paper. First the pseudo code:
for i = 1 to n
x = x + 1
j = n
while (j>1)
j = j/2
and my interpretation:
n/2 + 1
n/2
n/2
n/2 <– top part of summation for line 4 (the while loop)
Σ logn+2
i=1 <– bottom part of summation for line 4 (the while loop)
n/2 <– top part of summation for line 5 (body of the while loop)
Σ logn+1
i=1 <– bottom part of summation for line 5 (body of the while loop)
So the first three lines in step count aren’t bad to see, but then the two summations inside the loop are a bit tricky to me. So for the first one logn + 2 I can split into two steps:
n/2
Σ 2
i=1
and
n/2
Σ logn
i=1
so I’m used to dealing with straight summation of n, not n/2. But I’ll give it a quick shot.
2*((n^2+n)/2) or rather just drop the fraction for this one so it’s straight: n^2+n.
Then for the logn piece:
logn*((n^2+n)/2) = ? Now I’m not really sure here. Not sure this even simplifies down at all. If anyone has any suggestions on this I’d appreciate it, but I think what I got there is it for this half. So I combine the two together to get my final answer for the first summation line 4 of the pseudo code:
logn * (n^2+n)/2 + n^2 + n
And for the second summation I think it would then be:
logn * n^2 + n
(can borrow a bit from what I had already completed above. Just dropped the part where I had 2 * (n^2+n)/2 and instead I’ll simply have two sets of the half which combine to make one n^2+n if that makes any sense I think?
Please let me know if I’ve totally lost it. Thank you!!
I think you’re analysis is a bit off. First, notice that what happens in the body of the
forloop is independent of the value ofiorx. So theforloop executesntimes and the same number of steps happen in theforloop body each time. The body of thewhileloop executes floor(log2(n)) times. That’s about all the analysis that’s needed. The result is n*floor(log2(n)). (If by “step” you mean statement executions, you need to modify this a bit to account for the number of statements in each loop body.)