Files
ProjectEulerPython/Problems/Problem1.py

85 lines
2.7 KiB
Python

#ProjectEuler/Python/Problem1.py
#Matthew Ellison
# Created: 01-26-19
#Modified: 07-23-21
#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) 2021 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
import math
class Problem1(Problem):
#Variables
__topNum = 999 #The largest number to be checked
#Functions
#Constructor
def __init__(self) -> None:
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) -> None:
#If the problem has already been solved do nothing and end the function
if(self.solved):
return
#Start the timer
self.timer.start()
#Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap
self.fullSum = self.__sumOfProgression(3) + self.__sumOfProgression(5) - self.__sumOfProgression(3 * 5)
#Stop the timer
self.timer.stop()
#Throw a flag to show the problem is solved
self.solved = True
#Reset the problem so it can be run again
def reset(self) -> None:
super().reset()
self.fullSum = 0
#Gets
#Returns the result of solving the problem
def getResult(self):
self.solvedCheck("result")
return f"The sum of all numbers < {self.__topNum + 1} is {self.fullSum}"
#Returns the requested sum
def getSum(self) -> int:
self.solvedCheck("sum")
return self.fullSum
#Gets the sum of the progression of the multiple
def __sumOfProgression(self, multiple: int) -> int:
numTerms = math.floor(self.__topNum / multiple) #Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap
#The sum of progression formula is (n / 2)(a + l). n = number of terms, a = multiple, l = last term
return int((numTerms / 2) * (multiple + (numTerms * multiple)))
"""Results:
The sum of all numbers < 1000 is 233168
It took an average of 2.293 microseconds to run this problem through 100 iterations
"""