Files
ProjectEulerPython/Problems/Problem1.py

94 lines
2.9 KiB
Python

#ProjectEuler/Python/Problem1.py
#Matthew Ellison
# Created: 01-26-19
#Modified: 07-17-20
#What is the sum of all the multiples of 3 or 5 that are less than 1000
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
"""
Copyright (C) 2020 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 Problems.Problem import Problem
from Stopwatch import Stopwatch
from Unsolved import Unsolved
class Problem1(Problem):
#Variables
__topNum = 999 #The largest number to be checked
#Functions
#Constructor
def __init__(self):
super().__init__("What is the sum of all the multiples of 3 or 5 that are less than 1000")
self.fullSum = 0 #The sum of all the numbers
#Operational functions
#Solve the problem
def solve(self):
#If the problem has already been solved do nothing and end the function
if(self.solved):
return
#Start the timer
self.timer.start()
#Check every number < 1000 to see if it is a multiple of 3 or 5. If it is add it to the running sum
#Add one to topNum because range works on < instead of <=
for num in range(1, self.__topNum + 1):
if((num % 3) == 0):
self.fullSum += num
elif((num % 5) == 0):
self.fullSum += num
num += 1
#Stop the timer
self.timer.stop()
#Throw a flag to show the problem is solved
self.solved = True
#Save the results
self.result = "The sum of all number < " + str(self.__topNum + 1) + " is " + str(self.fullSum)
#Reset the problem so it can be run again
def reset(self):
super().reset()
self.fullSum = 0
#Gets
#Returns the requested sum
def getSum(self) -> int:
#If the problem hasn't been solved throw an exception
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the sum")
return self.fullSum
#If you are running this file, automatically start the correct function
if(__name__ == "__main__"):
problem = Problem1()
print(problem.getDescription()) #Print the description
problem.solve() #Call the function that answers the problem
#Print the results
print(problem.getResult())
print("It took " + problem.getTime() + " to solve this algorithm")
"""Results:
The sum of all the multiples of 3 or 5 is 233168
It took 114.142 microseconds to run this algorithm
"""