4
int foo(int n)
{
    int sum = 0;
    for(int k=1; k <= n; k = k * 2) 
    {
        sum += k;
    }
    return sum;
}

I have the following function. Now, according to me the runtime complexity of foo(n) should be big-o(logn). Now, I am asked to find out the run time complexity of foo(n*n*n*n). What should it be? According to me, it should be, big-o(logn) only. Am I right in saying this?

3
  • I am asked to find out the run time complexity of foo(nnn*n).What does it means? Commented Sep 15, 2014 at 7:16
  • What is the reason of donwvoting the question, I don't understand? Commented Sep 15, 2014 at 7:22
  • No reason to downvote, +1. Commented Sep 15, 2014 at 7:26

2 Answers 2

4

It is O(log n4) → O(4 log n) → O(log n)

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

1 Comment

Yes, I did it by that way only. Thanks. :)
4

Ask yourself, how many times does the loop execute? Create a table for the loop when the input is n:

for(int k=1; k <= n; k = k * 2)

  Iteration  |  k 
-------------+-----
      1      |  1
      2      |  2
      3      |  4
     ...     | ...
     ...     | ...
      k      |  n

2k = n → k = log(n)

Now you're asking for n4 input. Simply change the table to:

  Iteration  |  k 
-------------+-----
      1      |  1
      2      |  2
      3      |  4
     ...     | ...
     ...     | ...
      k      | n^4

2k = n4 → k = log(n4) = 4 * log(n)

10 Comments

@PaulR I'm giving OP a direction, not a full solution. I think my example should guide him to reach the answer.
He's already solved this part - read the whole question carefully.
I think it will be 8 corresponding to 3. However, it will be big-o(logn) for n^4 as well, right?
All good now - have an up-vote - sometimes the simplest questions can be the fiddliest! ;-)
Please note that the value of k after iteration i is actually 2^(i-1). So if k becomes equal to n after i iterations then the loop ran for i times which is the complexity of the code. 2^(i-1) = n, and now you can solve this for i.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.