Skip to content

Instantly share code, notes, and snippets.

@tpopp
Last active December 20, 2015 12:29
Show Gist options
  • Save tpopp/6131734 to your computer and use it in GitHub Desktop.
Save tpopp/6131734 to your computer and use it in GitHub Desktop.
3n + 1
import sys
values = {1:0}
def cycle(i, j):
large = 0
for k in range(min(i,j), max(i,j)+1):
a = compute(k)
if (a > large):
large = a
print(i, j, large+1) #(large + 1) because I wasn't including 1 in the length of the cycle.
def compute(k):
length = 0
temp = {}
temp[k] = length
while (not(values.__contains__(k))):
if (k%2 == 0):
k /= 2
else:
k = k*3 + 1
length += 1
temp[k] = length
for i in temp.keys():
values[i] = values[k] + length - temp[i]
return length + values[k]
def driver():
for line in sys.stdin.readlines():
i = line.split()[0]
j = line.split()[1]
cycle(i, j)
#too slow to do everycase. PyPy would probably be fast enough
#1 - 700,000 is limit in 3 sec
#1 - 1,000,000 takes a little bit over 4 sec.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment