2
\$\begingroup\$

My question is very simple.

I wrote this program for pure entertainment. It takes a numerical input and finds the length of every Collatz Sequence up to and including that number.

I want to make it faster algorithmically or mathematically (i.e. I know I could make it faster by running multiple versions parallel or by writing it in C++, but where's the fun in that?).

Any and all help is welcome, thanks!

from matplotlib import pyplot as plt
from tqdm import tqdm
# Get Range to Check, Make Memory
top_range = int(input('Top Range: '))
mem = [0] * (top_range + 1)
def collatz():
 for start in tqdm(range(2, top_range + 1)):
 # If mod(4) == 1: Value 2 or 3 Cached
 if start % 4 == 1:
 mem[start] = mem[(start + (start >> 1) + 1) // 2] + 3
 # If mod(4) == 3: Use Algorithm
 elif start % 4 == 3:
 num = start
 count = 0
 while num >= start:
 if num % 2:
 num += (num >> 1) + 1
 count += 2
 else:
 num //= 2
 count += 1
 mem[start] = mem[num] + count
 # If mod(4) == 2 or 4: Value 1 Cached
 else:
 mem[start] = mem[(start // 2)] + 1
collatz()
# 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()
asked Dec 9, 2021 at 16:49
\$\endgroup\$

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.