GATE Computer ScienceVery hardGATE CS (PYQ pattern)

How many times does x++ execute? for (i = 1; i <= 200; i++) { j = 1; while (j <= i) { x++; j *= 3; } }

  1. A. 862
  2. B. 906
  3. C. 1000
  4. D. 884

Correct answer: D. 884

For a given i the loop runs ⌊log₃ i⌋ + 1 times: 1 time for i = 1, 2; 2 times for i = 3…8; 3 times for 9…26; 4 times for 27…80; 5 times for 81…200 (120 values). The sum is 2 + 12 + 54 + 216 + 600 = 884.

More Algorithms questions

Exams that ask this topic