ProgrammingVery hardGoldman Sachs OA · Amazon OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Function J(Integer n, Integer k)
    if (n == 1)
        return 0
    end if
    return (J(n - 1, k) + k) mod n
End Function
Print J(7, 3) + 1
  1. A. 4
  2. B. 7
  3. C. 3
  4. D. 6

Correct answer: A. 4

This is the Josephus recurrence: J(1) = 0, J(2) = 1, J(3) = 1, J(4) = 0, J(5) = 3, J(6) = 0, J(7) = 3 (0-based). Adding 1 gives the 1-based survivor: 4.

More Pseudocode and Code Tracing questions

Exams that ask this topic