GATE Computer ScienceVery hardGATE CS (PYQ pattern)

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

  1. A. 254
  2. B. 247
  3. C. 127
  4. D. 448

Correct answer: B. 247

For i = 2^a the inner two loops run Σ_{j=1}^{i} (⌊log₂(i/j)⌋ + 1) = 2i − 1 times (e.g. i = 2: 2 + 1 = 3). Summing over i = 1, 2, …, 64: (2 + 4 + … + 128) − 7 = 254 − 7 = 247. Dropping the −1 gives 254.

More Algorithms questions

Exams that ask this topic