The Collatz sequence rules are as follows:
- If n = odd: n = 3n + 1
- If n = even: n = n/2
I am a student with a basic level of python and need to minimise the number of numbers I check to find the longest sequence less than 100. I need to output the starting term of said sequence. Both even numbers and multiples of five can be the answer (if you are looking at answers less than 20 the answer is 18) and am unsure what to check).
Code below works but checks 100 numbers:
highest = 0
highest_num = 0
def Collatz(num, highest, highest_num):
iterations = 0
while num!=1:
if num%2 == 0:
num//=2
else:
num = 3*num + 1
iterations += 1
if iterations > highest:
highest = iterations
highest_num = i
print(highest_num)
return highest, highest_num
for i in range(1, 101, 1):
result = Collatz(i, highest, highest_num)
highest = result[0]
highest_num = result[1]
P.S The answer is 97
You can save result of previously computed numbers is some dict and then use it when you reach some of that numbers. Here is sample code:
Time comparision: