GATE Computer ScienceHardGATE CS

How many times is x++ executed by the following code? for (i = 1; i <= 100; i++) for (j = 1; j <= 100; j += i) x++;

  1. A. 482
  2. B. 518
  3. C. 573
  4. D. 600

Correct answer: C. 573

For a fixed i the inner loop runs for j = 1, 1 + i, 1 + 2i, ..., so it executes ⌈100/i⌉ times, not ⌊100/i⌋. Summing ⌈100/i⌉ over i = 1 to 100 gives 573; the floor sum 482 is the trap.

More Algorithms questions

Exams that ask this topic