Data Structures & AlgorithmsVery hardGATE CS · Codeforces Div 2 B

Consider this recursive function:

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

Correct answer: B. 21

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

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic