GATE Computer ScienceHardGATE CS (PYQ pattern)

How many times is x++ executed? for (i = 2; i <= 100; i++) for (j = i*i; j <= 100; j += i) x++;

  1. A. 283
  2. B. 146
  3. C. 246
  4. D. 142

Correct answer: B. 146

The inner loop runs only for i ≤ 10 (i² ≤ 100), and then ⌊(100 − i²)/i⌋ + 1 times: i = 2…10 give 49, 31, 22, 16, 11, 8, 5, 3, 1 = 146. Starting j at 2i instead of i² gives 283; letting i start at 1 adds 100 (246); using j < 100 gives 142.

More Algorithms questions

Exams that ask this topic