Skip to content
Official PYQ · 2014

GATE CS 2014 Set 2 Q10 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Consider the function func shown below: 

int func(int num) { 
   int count = 0; 
   while (num) { 
     count++; 
     num>>= 1; 
   } 
   return (count); 
} 

The value returned by func(435435) is ________

View worked solution

Answer: 9

The given function func(num) counts the number of bits in the binary representation of the positive integer num by repeatedly right-shifting it by 1 bit (which is equivalent to integer division by 2) until num becomes 0.

Mathematically, the value returned for any positive integer nn is given by:

count=⌊log⁡2(n)⌋+1\text{count} = \lfloor \log_2(n) \rfloor + 1

For num=435num = 435:

  • We know that 28=2562^8 = 256 and 29=5122^9 = 512.
  • Since 256≤435<512256 \le 435 < 512, the binary representation of 435435 requires exactly 99 bits.

Let's trace the loop step-by-step:

Iteration Initial num (Decimal) count (After increment) Next num (After num >>= 1)
14351217
22172108
3108354
454427
527513
61366
7673
8381
9190

When num becomes 0, the while loop terminates, and the function returns count, which is 9.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions