ZHAWNotes/Notes/Semester 2/THIN - Theoretische Informatik/collatz.py

41 lines
940 B
Python

from time import time
result = 0
maxIterations = 0
cache = dict()
start_time = time()
def printTime(sec: int):
mins = sec // 60
hours = mins // 60
mins = mins % 60
sec = sec % 60
print("Time: %02d:%02d:%02d" % (hours, mins, sec))
def collatz(value: int):
currentValue = value
if (value not in cache):
if (currentValue % 2 == 0):
currentValue //= 2
else:
currentValue = (currentValue * 3) + 1
if (currentValue == 1):
cache[value] = 1
else:
cache[value] = 1 + collatz(currentValue)
return cache[value]
for i in range(1, 50 * 1000 * 1000):
iterations = collatz(i)
if (iterations > maxIterations):
maxIterations = iterations
result = i
end_time = time()
print("The number with the most iterations is " + str(result) + " with " + str(maxIterations) + " iterations.")
printTime(end_time - start_time)