Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Ackermann's function grows faster than any primitive-recursive function. Compute A(2, 3) and count the recursive calls.

Problem: Ackermann's function grows faster than any primitive-recursive function. Compute A(2, 3) and count the recursive calls.
import sys
sys.setrecursionlimit(10000)
calls = 0
def A(m, n):
    global calls
    calls += 1
    if m == 0: return n + 1
    if n == 0: return A(m - 1, 1)
    return A(m - 1, A(m, n - 1))
print(A(2, 3), calls)
What is printed?
  1. A. 9 44
  2. B. 7 44
  3. C. 9 27
  4. D. 11 106

Correct answer: A. 9 44

A(1, n) = n + 2 and A(2, n) = 2n + 3, so A(2, 3) = 9, yet the recursion makes 44 calls because every level re-expands the levels below it. A(4, 2) already has 19,729 digits.

More Coding Interview Problems questions

Exams that ask this topic