Inspired by Joe Knapp's Collatz conjecture email.
In [1]:
def collatz_sequence(n):
while True:
yield n
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
In [2]:
for i, x in enumerate(collatz_sequence(9)):
print(i, x)
if x == 1:
break
In [3]:
def stopping_power(n):
for i, n in enumerate(collatz_sequence(n)):
if n == 1:
return i
In [4]:
known_stopping_power = {
27: 111,
9: 19,
97: 118,
871: 178,
6171: 261,
77031: 350,
}
for n, s in known_stopping_power.items():
assert stopping_power(n) == s, f'{n}, {s}, {stopping_power(n)}'