Skip to content

Instantly share code, notes, and snippets.

@anivarth
Last active May 5, 2016 16:54
Show Gist options
  • Save anivarth/d527d818446c2097ebec26c1a2686e51 to your computer and use it in GitHub Desktop.
Save anivarth/d527d818446c2097ebec26c1a2686e51 to your computer and use it in GitHub Desktop.
Project Euler Problem 14 Solution with Python
#http://radiusofcircle.blogspot.com
#time module for calculating execution time
import time
#time at the start of program execution
start = time.time()
#dictionary with all the values initialized to 0
dic = {n: 0 for n in xrange(1,1000000)}
#Entering the values of 1 and 2
dic[1] = 1
dic[2] = 2
#for loop find find the size of collatz sequences
for n in xrange(3,1000000,1):
#counter to count the size for each iteration
counter = 0
#original number
original_number = n
#while loop to do collatz iterations
while n > 1:
#check if the number is a previous sequence
if n < original_number:
#Size of collatz sequence for the iteration
dic[original_number] = dic[n] + counter
break
#collatz sequence conditions
if n%2 == 0:
n = n/2
counter += 1
else:
n = 3*n+1
counter += 1
#dic.values() will give the values of the dictionary
#list.index(some_number) will output the index
#of the number. As the index starts from 0
#we are adding one to the index.
print dic.values().index(max(dic.values()))+1
#time at the end of execution
end = time.time()
#printing the total time of execution
print end-start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment