Last active
May 5, 2016 16:54
-
-
Save anivarth/d527d818446c2097ebec26c1a2686e51 to your computer and use it in GitHub Desktop.
Project Euler Problem 14 Solution with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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