Data Structures & AlgorithmsVery hardProduct company OA

A memoised recursion f(n) = f(n//2) + f(n//3) + f(n//6) is evaluated for n = 10¹². How many distinct calls (cache misses) are made?

A memoised recursion f(n) = f(n//2) + f(n//3) + f(n//6) is evaluated for n = 10¹². How many distinct calls (cache misses) are made?
from functools import lru_cache
calls = 0
@lru_cache(None)
def f(n):
    global calls; calls += 1
    if n == 0: return 1
    return f(n // 2) + f(n // 3) + f(n // 6)
print(f(10**12) > 0, calls)
  1. A. True 40
  2. B. True 1000000
  3. C. True 438
  4. D. True 1365

Correct answer: C. True 438

Floor division composes: ⌊⌊n/a⌋/b⌋ = ⌊n/(ab)⌋, so every reachable argument has the form ⌊n / (2ᵃ·3ᵇ)⌋ (6 = 2·3 adds nothing new). There are only about 40 × 25 pairs (a, b), and many give the same quotient: exactly 438 states including 0. So the memo turns an exponential call tree (≈ 3^depth) into O(log² n) work. 1365 ignores the coincidences; a dense DP table of size n is impossible.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic