Skip to content

Instantly share code, notes, and snippets.

@chuckha
Created May 6, 2016 01:36
Show Gist options
  • Save chuckha/c0573b55387cc10d1b314d76a11ac3d8 to your computer and use it in GitHub Desktop.
Save chuckha/c0573b55387cc10d1b314d76a11ac3d8 to your computer and use it in GitHub Desktop.
lookup = {}
def collatz(start, iteration):
if start == 1:
return iteration + 1
if start in lookup:
return collatz(lookup[start], iteration + 1)
if start % 2 == 0:
lookup[start] = start / 2
return collatz(lookup[start], iteration + 1)
else:
lookup[start] = start * 3 + 1
return collatz(lookup[start], iteration + 1)
class Largest(object):
def __init__(self, iterations=0, number=0):
self.number = number
self.iterations = iterations
def update(self, number, iterations):
self.number = number
self.iterations= iterations
def __str__(self):
return "{} has {} iterations".format(self.number, self.iterations)
largest = Largest()
for i in xrange(1, 10**6):
num_iterations = collatz(i, 0)
if num_iterations > largest.iterations:
largest.update(i, num_iterations)
print(largest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment