-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollatz.py
More file actions
55 lines (41 loc) · 1003 Bytes
/
Copy pathcollatz.py
File metadata and controls
55 lines (41 loc) · 1003 Bytes
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
44
45
46
47
48
49
50
51
52
53
54
55
#
# Collatz cycles to 100k or argv[1]
# @spiralbend 2025-06-25
#
import sys
import time
start = time.time()
upto = int(sys.argv[1]) if len(sys.argv) > 1 else 100_000
counter = {}
memo = {}
def main():
for seed in range(1, upto + 1):
counter[seed] = co_length(seed)
max_seed = max(counter, key=counter.get)
nice = make_cycle(max_seed)
print(
f"The prize for under {upto} belongs to {max_seed} with "
f"{counter[max_seed]} steps:\n{nice}"
)
print(f"Elapsed time: {time.time() - start:.4f} seconds")
def co_length(n):
if n == 1:
return 1
elif n in memo:
return memo[n]
elif n % 2 == 0:
next_n = n // 2
else:
next_n = 3 * n + 1
memo[n] = 1 + co_length(next_n)
return memo[n]
def make_cycle(n):
nodes = [n]
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
nodes.append(n)
return " → ".join(str(x) for x in nodes)
main()