#ProjectEuler/Python/Problem2.py #Matthew Ellison # Created: 01-26-19 #Modified: 10-30-20 #The sum of the even Fibonacci numbers less than 4,000,000 #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 . """ from Problems.Problem import Problem from Algorithms import getAllFib from Unsolved import Unsolved class Problem2(Problem): #Variables __topNumber = 4000000 - 1 #Functions #Constructor def __init__(self): super().__init__("What is the sum of the even Fibonacci numbers less than 4,000,000?") self.fullSum = 0 #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() #Get a list of all fibonacci numbers < 4,000,000 fibNums = getAllFib(self.__topNumber) #Send it - 1 because it is < __topNumber #Step through every element in the list checking if it is even for num in fibNums: #If the number is even add it to the running tally if((num % 2) == 0): self.fullSum += num #Stop the timer self.timer.stop() #Throw a flag to show the problem is solved self.solved = True #Reset the problem def reset(self): super().reset() self.fullSum = 0 #Gets #Returns the result of solving the problem def getResult(self): #If the problem hasn't been solved throw an exception if(not self.solved): raise Unsolved("You must solve the problem before you can see the result") return f"The sum of all even Fibonacci numbers less than {self.__topNumber + 1} is {self.fullSum}" #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 """Results: The sum of all even Fibonacci numbers less than 4000000 is 4613732 It took an average of 10.286 microseconds to run this problem through 100 iterations """