ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode? (All variables are integers, so / is integer division.)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division.)
Function f(Integer n)
    if (n < 10)
        return n
    end if
    return f(f(n / 10) + n mod 10)
End Function

Print f(9875)
  1. A. 11
  2. B. 5
  3. C. 29
  4. D. 2

Correct answer: D. 2

f(n) reduces n to a single digit (its digital root). f(98) = f(9 + 8) = f(17) = 8. f(987) = f(8 + 7) = f(15) = 6. f(9875) = f(6 + 5) = f(11) = 2. The plain digit sum 29 is the trap.

More Pseudocode and Code Tracing questions

Exams that ask this topic