GATE Computer ScienceHardGATE CS (PYQ pattern)

int ds(int n) { return n < 10 ? n : ds(n / 10) + n % 10; } int steps(int n) { int c = 0; while (n >= 10) { n = ds(n); c++; } return c; } What is the sum of steps(n) for n = 1 to 999?

  1. A. 1815
  2. B. 1765
  3. C. 1935
  4. D. 999

Correct answer: A. 1815

Each step replaces n by its digit sum until n < 10; a number below 10 takes 0 steps, most others 1 or 2 (99 and 999 style cases take 2). Summing steps(n) over 1..999 by program gives 1815.

More Programming and Data Structures (GATE) questions

Exams that ask this topic