Updated problem 1 algorithm

This commit is contained in:
2020-10-26 14:44:43 -04:00
parent ed85338bf2
commit dfe5aa47f6

View File

@@ -1,7 +1,7 @@
#ProjectEuler/Python/Problem1.py
#Matthew Ellison
# Created: 01-26-19
#Modified: 07-17-20
#Modified: 10-26-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
"""
@@ -23,8 +23,8 @@
from Problems.Problem import Problem
from Stopwatch import Stopwatch
from Unsolved import Unsolved
import math
class Problem1(Problem):
@@ -47,13 +47,8 @@ class Problem1(Problem):
#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
#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()
@@ -75,6 +70,11 @@ class Problem1(Problem):
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the 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)))
#If you are running this file, automatically start the correct function
@@ -88,5 +88,5 @@ if(__name__ == "__main__"):
"""Results:
The sum of all numbers < 1000 is 233168
It took an average of 102.336 microseconds to run this problem through 100 iterations
It took an average of 2.293 microseconds to run this problem through 100 iterations
"""