Files
ProjectEulerPython/Problem30.py

77 lines
2.9 KiB
Python

#ProjectEuler/Python/Problem30.py
#Matthew Ellison
# Created: 10-28-19
#Modified: 10-28-19
#Find the sum of all the numbers that can be written as the sum of the fifth powers of their digits.
#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
#Setup the variables
__TOP_NUM = 1000000 #This is the largest number that will be checked
__BOTTOM_NUM = 2 #Starts with 2 because 0 and 1 don't count
__POWER_RAISED = 5 #This is the power that the digits are raised to
#Returns a list with the individual digits of the number passed to it
def getDigits(num: int) -> list:
listOfDigits = [] #This list holds the individual digits of num
#The easiest way to get the individual digits of a number is by converting it to a string
digits = str(num)
#Start with the first digit, convert it to an integer, store it in the list, and move to the next digit
for cnt in range(0, len(digits)):
listOfDigits.append(int(digits[cnt]))
#Return the list of digits
return listOfDigits
def Problem30():
sumOfFifthNumbers = [] #This is a list of the numbers that are the sum of the fifth power of their digits
#Start with the lowest number and increment until you reach the largest number
for currentNum in range(__BOTTOM_NUM, __TOP_NUM):
#Get the digits of the number
digits = getDigits(currentNum)
#Get the sum of the powers
sumOfPowers = 0
for cnt in range(0, len(digits)):
sumOfPowers += digits[cnt]**__POWER_RAISED
#Check if the sum of the powers is the same as the number
#If it is add it to the list, otherwise continue to the next number
if(sumOfPowers == currentNum):
sumOfFifthNumbers.append(currentNum)
#Print the results
print("The sum of all the numbers that can be written as the sum of the fifth powers of their digits is " + str(sum(sumOfFifthNumbers)))
#This calls the appropriate functions if the script is called stand alone
if __name__ == "__main__":
timer = Stopwatch()
timer.start()
Problem30()
timer.stop()
print("It took " + timer.getString() + " to run this algorithm")
""" Results:
The sum of all the numbers that can be written as the sum of the fifth powers of their digits is 443839
It took 3.284 seconds to run this algorithm
"""