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 % 3 == 0:
f(n - 2)How many times is f called in total, including the initial call, when f(10) is made?- A. 177
- B. 30
- C. 88
- D. 29
Correct answer: D. 29
Each call makes one call to f(n − 1) and a second call only when n is divisible by 3; counting every invocation gives 29. Forgetting the divisibility test gives 177, and counting only the calls that are not the initial one gives 28.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Consider this function: python def g(n): if n < 3: return n if n % 2 == 0: return g(n - 3) + g(n - 4) return g(n - 3) - 1 What value does…
- An undirected graph has the vertices G, J, K, M, P, U, V, W and the edges W–U, W–J, W–M, W–G, U–V, U–M, V–K, J–G, K–G, P–M, P–G, M–G. What…
- A grid has 8 rows and 7 columns (rows listed top to bottom; '.' is an open cell, '#' a wall): ..#.... .#..... ..#.##. .#....# .#…
- Floyd–Warshall runs on vertices 1 to 5 with these arcs u→v (weight): 1→2 (4), 1→3 (1), 2→3 (11), 2→4 (2), 2→5 (2), 3→1 (6), 3→2 (4), 4→2…
- A connected undirected graph has the vertices E, F, I, Q, S, Z and weighted edges (weights in brackets): E–I (3), F–E (8), Z–S (12), S–I…
- A directed weighted graph has the arcs u→v (weight): Z→G (12), G→Z (1), G→T (11), G→A (3), G→S (7), T→Z (11), T→M (1), A→Z (13), A→T (11)…