GATE Computer ScienceVery hardGATE CS (PYQ pattern)

How many times does x++ execute? for (i = 1; i < 200; i *= 2) for (j = i; j < 200; j += i) x++;

  1. A. 400
  2. B. 1600
  3. C. 393
  4. D. 399

Correct answer: C. 393

For i = 2^k the inner loop runs ⌈(200 − i)/i⌉ times: 199, 99, 49, 24, 12, 6, 3, 1 for i = 1, 2, 4, …, 128. The sum is 393, far below the n log n = 1600 that a careless bound suggests.

More Algorithms questions

Exams that ask this topic