Question was like,
Starting with any positive integer N, Collatz sequence is defined corresponding to n as the numbers formed by the following operations :
If n is even, then n = n / 2.
If n is odd, then n = 3*n + 1.
Repeat above steps, until it becomes 1.
How many steps to reach from N to 1? e.g. 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 takes 7 steps.
The top-down recursive with memoization is like
def answer(n):
@cache
def rec(n):
if n == 1:
return 0
if n % 2 == 0:
return 1 + rec(n / 2)
return 1 + rec(3 * n + 1)
return rec(n)This was my solution. How would you turn this to an iterative DP solution?