1

Assume algo(p) is an algorithm that take Theta(p) time to execute and does not change p. Determine the running time complexity of the following algorithm:

Algo2(n) 
begin
p=1;
while p <= n 
    begin 
    algo(p)
    p=2*p
    end;
end;

Really have no idea where to begin, I was thinking O(logn) maybe since p=p*2 but then there is an algo(p) in the while loop and I don't know how that would effect things.

2
  • How did you get log(n) from p = p*2 Commented Oct 15, 2014 at 21:09
  • @TwilightSparkleTheGeek Read the answer given by Henrik, he explains why the answer to this problem is Theta(n). Commented Oct 18, 2014 at 13:45

2 Answers 2

3

It's Big Theta(n):

It calls algo(p) O(logn) times with p = 1, 2, 4, ..., 2^(floor(logn)). This is Theta(1 + 2 + ... + 2^(floor(logn)) = Theta(2^(floor(logn+1)-1) = Theta(n).

Sign up to request clarification or add additional context in comments.

1 Comment

what does floor mean exactly?
0

To get an easier problem, you can set it like this :

Algo(n)
  begin
  p=1, i=1
  while p<= n
    begin
    algo(p)
    p=2*p
    i++
    end
  end

which you can rewrite like that :

Algo(n)
  begin
  i=1
  while 2^(i-1)<=n
    begin
    algo(2^(i-1))
    i++
    end
  end

Then, as Henrik said :

It calls algo(p) O(logn) times with p = 1, 2, 4, ..., 2^(floor(logn)). This is Theta(1 + 2 + ... + 2^(floor(logn)) = Theta(2^(floor(logn+1)-1) = Theta(n).

2 Comments

That's not correct. The loop is executed O(logn) times, but the complexity of the whole algortithm including the calls to algo is Theta(n).
I misread his post. I'll correct my answer, thanks for pointing it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.