ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode?

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

Correct answer: B. 6

f computes 6! mod 7 = 720 mod 7 = 6, reducing at every step so numbers stay small. By Wilson's theorem (p − 1)! ≡ −1 ≡ p − 1 (mod p) for prime p. The recursion is tail-recursive: the result is passed down in acc.

More Pseudocode and Code Tracing questions

Exams that ask this topic