GATE Computer ScienceEasyGATE CS (PYQ pattern)

How many times is x++ executed? for (i = 1; i <= 1000; i *= 2) for (j = i; j >= 1; j /= 3) x++; (integer division)

  1. A. 55
  2. B. 28
  3. C. 34
  4. D. 44

Correct answer: C. 34

i takes the 10 values 1, 2, 4, …, 512. For each, the inner loop runs ⌊log₃ i⌋ + 1 times: 1, 1, 2, 2, 3, 4, 4, 5, 6, 6 for i = 1, 2, 4, …, 512, total 34 (e.g. i = 512: 512, 170, 56, 18, 6, 2). Halving instead of dividing by 3 gives 55; the condition j > 1 gives 28.

More Algorithms questions

Exams that ask this topic