Files
ProjectEulerPython/Problem14.py

81 lines
2.9 KiB
Python

#ProjectEuler/Python/Problem14.py
#Matthew Ellison
# Created: 01-31-19
#Modified: 03-28-19
"""
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Which starting number, under one million, produces the longest chain?
"""
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
"""
Copyright (C) 2019 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from Stopwatch import Stopwatch
__topNum = 1000000 #The largest number that you will check against the chain
#This function returns a list of numbers created by the chain
def getChain(startNum: int) -> list:
#Put the starting number in the list
chain = [startNum]
#Starting with the current number perform the correct opperations on the numbers until that number reaches 1
while(startNum > 1):
#Determine if the number is odd or even and perform the correct operation and add the new number to the list
if((startNum % 2) == 0):
startNum /= 2
else:
startNum = (3 * startNum) + 1
#Add the new number to the chain
chain.append(startNum)
#Return the list
return chain
def Problem14():
#Setup your variables
largestChain = [] #Holds the longest chain of numbers
#Start at 1 and run up to 1000000, checking how long the chain is when started with each number
for startingNumber in range(1, __topNum):
currentChain = getChain(startingNumber) #Get the chain
#If the new chain is longer than the current longest chain replace it
if(len(currentChain) > len(largestChain)):
largestChain = currentChain.copy()
#Print the results
print("The longest chain with a starting number < " + str(__topNum) + " is " + str(largestChain[0]) + " with a length of " + str(len(largestChain)))
#If you are running this file, automatically start the correct function
if __name__ == "__main__":
timer = Stopwatch() #Determines the algorithm's run time
timer.start() #Start the timer
Problem14() #Call the function that answers the question
timer.stop() #Stop the timer
#Print the results of the timer
print("It took " + timer.getString() + " to run this algorithm")
"""Results:
The longest chain with a starting number < 1000000 is 837799 with a length of 525
It took 28.893 seconds to run this algorithm
"""