ma/experiments/collatz.py

32 lines
719 B
Python

import time
def collatz(x):
seq = [x]
while x != 1:
if x % 2 == 0:
x //= 2
else:
x = 3 * x + 1
seq.append(x)
return seq
if __name__ == "__main__":
best = None
try:
i = 1
start = time.time()
while True:
pair = (i, collatz(i))
if (not best or len(pair[1]) > len(best[1])) and not any(c >= 2**31 for c in pair[1]):
best = pair
if i % 10000 == 0:
now = time.time()
print(f"{i:>10} best: {best[0]:>10} {len(best[1]):>5} {(now - start) * 1000 / i:5.2}ns/seq")
i += 1
except KeyboardInterrupt:
pass
print(best)