-8
k = n; //integer division
while(k > 1) {
    std::cout << k; 
    k=k/2;
}

I need to find out the asymptotic estimate as a function of n.

stardust
  • 5,918
  • 1
  • 18
  • 20
  • 4
    And the question is....? – WhozCraig May 01 '13 at 16:09
  • The question is that i need the asymptotic estimate of that function. – user2340034 May 01 '13 at 16:13
  • @user2340034: And I need to eat, otherwise I will die of starvation. The previous sentence I wrote isn't a question, it is a statement, and neither is what you have written twice. Please edit this to ask a question that someone else can answer. Code + "I need something" isn't a valid Stack Overflow question. – talonmies May 01 '13 at 16:43
  • 1
    @talonmies: Do you honestly think that it makes a big difference to phrase something as: "What is XXX?" instead of "I need XXX."? I find it insulting to be treated like a brainless compiler that can only recognize a question if precisely the correct syntax and punctuation are used. – Jerry Coffin May 01 '13 at 16:55
  • Actually, the primary problem here is that “asymptotic estimate” is not a clear term. On the face of it, it appears to refer to the value of a function, not the computational complexity of an algorithm. – Eric Postpischil May 01 '13 at 18:23

1 Answers1

2

The complexity is logarithmic.

Assuming K is non-negative, division by two is equivalent to shifting right by one bit. Therefore, the maximum number of iterations before k becomes 0 is the number of bits in k. More specifically, the position of the most significant bit in k that is set (i.e., a 1) will determine the number of iterations executed in the loop.

Since the operations in the loop are (presumably) constant complexity, logarithmic number of iterations leads directly to logarithmic complexity.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111