Data Structures & AlgorithmsHardCodeforces Div 2 C · GATE CS

Consider this recursive function:

Consider this recursive function:
def f(n):
    if n <= 1:
        return
    f(n - 1)
    if n % 2 == 0:
        f(n - 2)
How many times is f called in total, including the initial call, when f(9) is made?
  1. A. 38
  2. B. 39
  3. C. 40
  4. D. 109

Correct answer: B. 39

Each call makes one call to f(n − 1) and a second call only when n is divisible by 2; counting every invocation gives 39. Forgetting the divisibility test gives 109, and counting only the calls that are not the initial one gives 38.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic