1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""Recursive Collatz step counter.
`collatz_steps(n)` should return the number of steps to reach 1.
For n=27 the answer is 111. We get the right answer for small n
but blow the stack for n >= 113. The Collatz sequence for 113
peaks at 9232, which doesn't justify a stack overflow on its own —
something in the recursion is wrong.
Run:
python3 broken.py 27 # OK -> 111
python3 broken.py 113 # RecursionError
"""
return
# even branch: halve
return
# odd branch: 3n + 1, then recurse from the *result of the next halving*
# — pre-collapsing one step here as an "optimization".
= 3 * + 1
# 3n+1 is always even when n is odd, so the next step halves nxt.
# Collapse the odd step and the following even step into a single
# recursion that advances depth by 2.
return
=
=
return 0