【发布时间】:2022-01-14 10:36:42
【问题描述】:
我的问题很简单。
我写这个程序纯粹是为了娱乐。它接受一个数字输入并找到每个 Collatz 序列的长度,直到并包括该数字。
我想在算法或数学上让它更快(即我知道我可以通过并行运行多个版本或用 C++ 编写它来让它更快,但那有什么乐趣呢?)。
欢迎任何帮助,谢谢!
编辑: 在 dankal444 的帮助下进一步优化代码
from matplotlib import pyplot as plt
import numpy as np
import numba as nb
# Get Range to Check
top_range = int(input('Top Range: '))
@nb.njit('int64[:](int_)')
def collatz(top_range):
# Initialize mem
mem = np.zeros(top_range + 1, dtype = np.int64)
for start in range(2, top_range + 1):
# If mod4 == 1: (3x + 1)/4
if start % 4 == 1:
mem[start] = mem[(start + (start >> 1) + 1) // 2] + 3
# If 4mod == 3: 3(3x + 1) + 1 and continue
elif start % 4 == 3:
num = start + (start >> 1) + 1
num += (num >> 1) + 1
count = 4
while num >= start:
if num % 2:
num += (num >> 1) + 1
count += 2
else:
num //= 2
count += 1
mem[start] = mem[num] + count
# If 4mod == 2 or 0: x/2
else:
mem[start] = mem[(start // 2)] + 1
return mem
mem = collatz(top_range)
# Plot each starting number with the length of it's sequence
plt.scatter([*range(1, len(mem) + 1)], mem, color = 'black', s = 1)
plt.show()
【问题讨论】:
-
也许这更适合Code Review(这是另一个 Stack Exchange 社区)。
标签: python algorithm performance math collatz