GATE Computer ScienceVery hardGATE CS (PYQ pattern)

void p(int n) { if (n == 0) return; printf("%d ", n); p(n - 1); printf("%d ", n * 10); if (n % 2 == 0 && n > 2) p(n - 2); } How many numbers does p(6) print, and what is their sum?

  1. A. 28 numbers, sum 407
  2. B. 40 numbers, sum 506
  3. C. 20 numbers, sum 341
  4. D. 28 numbers, sum 347

Correct answer: A. 28 numbers, sum 407

Let N(n) be the count printed by p(n): N(0) = 0 and N(n) = 2 + N(n - 1), plus N(n - 2) when n is even and n > 2. So N(1) = 2, N(2) = 4, N(3) = 6, N(4) = 8 + 4 = 12, N(5) = 14, N(6) = 16 + 12 = 28. Every call p(k) with k > 0 prints k and 10k (11k together); adding 11k over all calls gives 407. Making only the outermost call p(6) branch into p(4) (and that p(4) not branching again) gives 20 numbers.

More Programming and Data Structures (GATE) questions

Exams that ask this topic